本人最近在学习nio,做的两个小例子,用nio实现socket通讯
一个是NBServer.java,一个是NBClient.java
由nbclient发起连接,并向server发送数据,server将接收到的数据在返回给client
问题是:client发完数据后有异常
java.io.IOException: 远程主机强迫关闭了一个现有的连接
请大家指教

解决方案 »

  1.   

    我的出错代码
    服务器端
    import java.io.*;
    import java.nio.*;
    import java.nio.channels.*;
    import java.nio.channels.spi.*;
    import java.net.*;
    import java.util.*; 
    import java.nio.charset.*; 
    /**
    *
    * @author Administrator
    * @version
    */
    public class NBTest1 
    {
    /** Creates new NBTest */
    public NBTest1()
    {
    }
    private static void acceptConnections() throws Exception 

    //Create the selector
    Selector selector = Selector.open();
    // Create the server socketchannel
    ServerSocketChannel server = ServerSocketChannel.open();
    // nonblocking I/O
    server.configureBlocking(false);
    // host-port 8000
    InetAddress host = InetAddress.getLocalHost(); 
    InetSocketAddress isa = new InetSocketAddress(host, 8000); 
    server.socket().bind(isa);
    System.out.println("Server attivo porta 8000");
    // register server to selector (type OP_ACCEPT)
    server.register(selector,SelectionKey.OP_ACCEPT);
    int keysAdded = 0; 
    // 用select()函数来监控注册在Selector上的SelectableChannel // 返回值代表了有多少channel可以进行IO操作 (ready for IO) while ((keysAdded = selector.select()) > 0)
    {
    System.out.println("keysAdded:"+keysAdded);
    // Waiting for events  
    selector.select();  
    // Get keys  
    Set keys = selector.selectedKeys();  
    Iterator i = keys.iterator();  
    // For each keys...
    while(i.hasNext()) 
    {    
    SelectionKey key = (SelectionKey) i.next();    
    // Remove the current key    
    i.remove();
    // if isAccetable = true
    // then a client required a connection
    if (key.isAcceptable()) 
    {
     // 从channel()中取得我们刚刚注册的channel。
    Socket socket = ((ServerSocketChannel)key.channel()).accept().socket();
    SocketChannel client = socket.getChannel();
    // Non Blocking I/O      
    client.configureBlocking(false);     
    // recording to the selector (reading)     
    client.register(selector, SelectionKey.OP_READ);      
    continue;    
    }
    // if isReadable = true   
    // then the server is ready to read 
    if (key.isReadable()) 
    {      
    SocketChannel client = (SocketChannel) key.channel();      
    // Read byte coming from the client      
    int BUFFER_SIZE = 32;      
    ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
    try 
    {        
    client.read(buffer);      
    }      
    catch (Exception e) 
    {        
    // client is no longer active        
    e.printStackTrace();        
    continue;  
    }
    // Show bytes on the console      
    buffer.flip();      
    Charset charset=Charset.forName("ISO-8859-1");      
    CharsetDecoder decoder = charset.newDecoder();      
    CharBuffer charBuffer = decoder.decode(buffer);      
    System.out.print("aa:"+charBuffer.toString());      
    continue;    
    }  
    }
    }//while
    //===========
    }
    /**
    * @param args the command line arguments
    */
    public static void main (String args[])
    {
    NBTest1 nbTest1 = new NBTest1();
    try
    {
    nbTest1.acceptConnections();
    }
    catch(Exception e)
    {
    e.printStackTrace();
    }
    }
    //===================
    }
    客户端
    import java.io.*;
    import java.nio.*;
    import java.nio.channels.*;
    import java.nio.channels.spi.*;
    import java.net.*;
    import java.util.*; 
    /**
    *
    * @author Administrator
    * @version
    */
    public class NBTest2 
    {
    /** Creates new NBTest */
    public NBTest2()
    {
    }
    private static void Connections() throws Exception
    {
    // Create client SocketChannel
    SocketChannel client = SocketChannel.open();
    //nonblockingI/O
    client.configureBlocking(false);
    // Connection to host port 8000
    InetAddress host = InetAddress.getLocalHost(); 
    client.connect(new java.net.InetSocketAddress(host,8000));
    // Create selector
    Selector selector = Selector.open();
    // Record to selector (OP_CONNECT type)
    SelectionKey clientKey = client.register(selector, SelectionKey.OP_CONNECT);
    // Waiting for the connection
    while (selector.select(500)> 0) 
    {
    // Get keys  
    Set keys = selector.selectedKeys();  
    Iterator i = keys.iterator();
    // For each key...  
    while (i.hasNext()) 
    {    
    SelectionKey key = (SelectionKey)i.next();
    // Remove the current key    
    i.remove();
    // Get the socket channel held by the key    
    SocketChannel channel =(SocketChannel)key.channel();
    // Attempt a connection    
    if (key.isConnectable()) 
    {
    // Connection OK      
    System.out.println("Server Found");
    // Close pendent connections
    if (channel.isConnectionPending())        
    channel.finishConnect();
    // Write continuously on the buffer      
    ByteBuffer buffer = null;
            
    buffer=ByteBuffer.wrap(new String("testnio").getBytes());
    channel.write(buffer);        
    buffer.clear();
     }//if
    }//while
    }//while
    }
     
    /**
    * @param args the command line arguments
    */
    public static void main (String args[])
    {
    NBTest2 nbTest2 = new NBTest2();
    try
    {
    nbTest2.Connections();
    }
    catch(Exception e)
    {
    e.printStackTrace();
    }
    }
    }