我现在做一个程序,很简单,就是把服务器收到数据后转发到另一个服务器,就相当与是一个代理的功能.现在遇到的问题如下:while (ite.hasNext())
{
SelectionKey oneKey = (SelectionKey)ite.next();
int rskOps = oneKey.readyOps();
if ((rskOps & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT)
{
ServerSocketChannel server = (ServerSocketChannel)oneKey.channel();
SocketChannel client = server.accept();
logBuf.put("New Connection from ").put(client.socket().toString());
logBuf.put("\n").flip();
logArea.append( logBuf.toString() );
logBuf.clear();
client.configureBlocking( false );
client.register( selector, SelectionKey.OP_READ);
//这个循环就是找到一个相对应要转发到哪个服务器
for(int i = 0;i < routeData.size();i++)
{
RouteData temp = (RouteData)routeData.get(i);
if(temp.getIfSetChannel() == false)
{
if(temp.setChannel(client, selector)) //关键问题是在这一步
{
break;
}
}
}
ite.remove(); }
}setChannel()代码如下:targetChannel = SocketChannel.open();
targetChannel.configureBlocking(false);
trgetChannel.connect(new InetSocketAddress("127.0.0.1",8888));
targetChannel.register(selector, SelectionKey.OP_READ);//测试代码-----------------
ByteBuffer buff = ByteBuffer.allocate(1024);
buff.putChar('a'); //这里就是问题所在点
buff.flip();
targetChannel.write(buff);
这里的targetChannel请求的链接对方已经响应了,并且分配了端口,但是这时候,这个代码会报异常: java.nio.channels.NotYetConnectedException
说是没有连接?很奇怪了,请问是什么原因?
{
SelectionKey oneKey = (SelectionKey)ite.next();
int rskOps = oneKey.readyOps();
if ((rskOps & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT)
{
ServerSocketChannel server = (ServerSocketChannel)oneKey.channel();
SocketChannel client = server.accept();
logBuf.put("New Connection from ").put(client.socket().toString());
logBuf.put("\n").flip();
logArea.append( logBuf.toString() );
logBuf.clear();
client.configureBlocking( false );
client.register( selector, SelectionKey.OP_READ);
//这个循环就是找到一个相对应要转发到哪个服务器
for(int i = 0;i < routeData.size();i++)
{
RouteData temp = (RouteData)routeData.get(i);
if(temp.getIfSetChannel() == false)
{
if(temp.setChannel(client, selector)) //关键问题是在这一步
{
break;
}
}
}
ite.remove(); }
}setChannel()代码如下:targetChannel = SocketChannel.open();
targetChannel.configureBlocking(false);
trgetChannel.connect(new InetSocketAddress("127.0.0.1",8888));
targetChannel.register(selector, SelectionKey.OP_READ);//测试代码-----------------
ByteBuffer buff = ByteBuffer.allocate(1024);
buff.putChar('a'); //这里就是问题所在点
buff.flip();
targetChannel.write(buff);
这里的targetChannel请求的链接对方已经响应了,并且分配了端口,但是这时候,这个代码会报异常: java.nio.channels.NotYetConnectedException
说是没有连接?很奇怪了,请问是什么原因?
SocketChannel channel;
channel = SocketChannel.open();
channel.configureBlocking(false);
channel.connect(new InetSocketAddress("localhost",8888));
channel.register(selector,SelectionKey.OP_READ);
System.out.println(channel.isConnected());//A 在第二个服务器接受第一个服务器的连接
(rskOps & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT分支里:
SocketChannel client = serverChannel.accept();
client.configureBlocking( false );
client.register( selector, SelectionKey.OP_READ );
System.out.println(client.isConnected());//B A处显示false B处显示true
加个这个