首页 新闻 会员 周边 捐助

java nio 简单例子出现 java.io.IOException: 远程主机强迫关闭了一个现有的连接错误

0
悬赏园豆:5 [已解决问题] 解决于 2015-11-25 15:51

--------server start-----
---new client connect----
message from client:-->java.io.IOException: 远程主机强迫关闭了一个现有的连接。
at sun.nio.ch.SocketDispatcher.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:43)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
at sun.nio.ch.IOUtil.read(IOUtil.java:197)
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:379)
at com.lzyer.newio.ServerThread.run(NioTcpServer4.java:69)
at java.lang.Thread.run(Thread.java:745)
Error in poll loop of server

求帮忙看一下,谢谢。

server:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

class ServerThread implements Runnable
{

    private Selector selector;

    private boolean running;

    public ServerThread(Selector selector)
    {
        this.selector = selector;
        this.running = true;
    }

    @Override
    public void run()
    {
        while (this.running)
        {
            try
            {
                while (this.selector.select() > 0)
                {
                    Iterator<SelectionKey> iter = this.selector.selectedKeys()
                            .iterator();

                    while (iter.hasNext())
                    {
                        SelectionKey key = iter.next();

                        iter.remove();

                        if (!key.isValid())
                            continue;

                        if (key.isAcceptable())
                        {
                            SocketChannel channel = ((ServerSocketChannel) key
                                    .channel()).accept();
                            channel.configureBlocking(false);
                            channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                            System.out.println("---new client connect----");
                            channel.write(ByteBuffer.wrap("hello client\n"
                                    .getBytes()));
                        }
                        else if (key.isReadable())
                        {

                            System.out.print("message from client:-->");

                            ByteBuffer buffer = ByteBuffer.allocate(1024);

                            SocketChannel channel = (SocketChannel) key
                                    .channel();

                            int len = 0;

                            while ((len = channel.read(buffer)) > 0)
                            {
                                buffer.flip();
                                System.out.println(new String(buffer.array(),
                                        0, len));
                                buffer.clear();
                            }

                            channel.register(selector, SelectionKey.OP_WRITE);
                        }
                        else if (key.isWritable())
                        {

                            SocketChannel channel = (SocketChannel) key
                                    .channel();
                            System.out.print("please enter:");
                            BufferedReader reader = new BufferedReader(
                                    new InputStreamReader(System.in));
                            String line = reader.readLine();
                            channel.write(ByteBuffer.wrap((line + "\n")
                                    .getBytes()));
                            channel.register(selector, SelectionKey.OP_READ);
                        }
                    }
                    Thread.sleep(2000);
                }
            }
            catch (Exception e)
            {
                this.running = false;
                System.out.println("Error in poll loop of server");
                // System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
    }

}

public class NioTcpServer4
{

    public static void main(String[] args)
    {
        ServerSocketChannel server = null;

        Selector selector = null;

        try
        {
            server = ServerSocketChannel.open();

            server.configureBlocking(false);

            server.bind(new InetSocketAddress(1001));

            selector = Selector.open();

            server.register(selector, SelectionKey.OP_ACCEPT);

            System.out.println("--------server start-----");

        }
        catch (Exception e)
        {
            System.err.println("server can't set up");
            e.printStackTrace();
            System.exit(1);
        }

        new Thread(new ServerThread(selector)).start();

    }

}

client:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

class ClientThread implements Runnable
{
    
    private Selector selector;
    
    private boolean running;

    public ClientThread(Selector selector)
    {
        
        this.selector = selector;
    }
    @Override
    public void run()
    {
        
        while(this.running)
        {
            try
            {
                while(selector.select()>0)
                {
                    Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                    
                    while(iter.hasNext())
                    {
                        
                        SelectionKey key = iter.next();
                        iter.remove();
                        if(key.isConnectable())
                        {
                            SocketChannel channel = (SocketChannel)key.channel();
                            channel.configureBlocking(false);
                            channel.finishConnect();
                            channel.register(this.selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                            System.out.println("+++++connect server success++++");
                            channel.write(ByteBuffer.wrap("hello client\n".getBytes()));
                        }else if(key.isReadable())
                        {
                            SocketChannel channel = (SocketChannel)key.channel();
                            
                            ByteBuffer buffer = ByteBuffer.allocate(1024);
                            
                            System.out.print("message from server:-->");
                            
                            int len=0;
                            while((len = channel.read(buffer))>0)
                            {
                                buffer.flip();
                                System.out.println(new String(buffer.array(), 0, len));
                                buffer.clear();
                            }
                            
                            channel.register(this.selector, SelectionKey.OP_WRITE);
                            
                        }else if(key.isWritable())
                        {
                            SocketChannel channel = (SocketChannel)key.channel();
                            
                            System.out.print("please enter:");
                            
                            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                            
                            String line = reader.readLine();
                            
                            channel.write(ByteBuffer.wrap((line+"\n").getBytes()));
                            
                            channel.register(this.selector, SelectionKey.OP_READ);
                            
                        }
                        
                    }
                    
                    Thread.sleep(2000);
                    
                }
                
            }catch(Exception e)
            {
                this.running = false;
                System.out.println("Error in poll loop of client");
                System.out.println(e.getMessage());
            }
            System.out.println("rttttt");
            
        }
  System.out.println("11111");
    }

}

public class NioTcpClient4
{

    public static void main(String[] args)
    {
        SocketChannel client = null;
        Selector selector = null;
        try
        {
            client = (SocketChannel)SocketChannel.open();
            client.configureBlocking(false);
            client.connect(new InetSocketAddress("localhost", 1001));
            selector = Selector.open();
            
            client.register(selector, SelectionKey.OP_CONNECT);
            
        }catch(Exception e)
        {
            System.out.println("client can't setup");
        }
        
        new Thread(new ClientThread(selector)).start();
        System.out.println("asa");
    }
}
lzyer的主页 lzyer | 初学一级 | 园豆:130
提问于:2015-11-25 00:28
< >
分享
最佳答案
0

ClientThread类中没有对running手动初始化,导致running一直为false

lzyer | 初学一级 |园豆:130 | 2015-11-25 15:50
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册