首页 文章

Java:套接字上的重新连接有时会出错

提问于
浏览
0

我正在制作一个原型客户端和服务器,以便我可以理解如何处理重新连接 . 服务器应该创建一个serversocket并永远倾听 . 客户端可以连接,发送其数据并关闭其套接字,但它不会向服务器发送"I'm done and closing"类型的消息 . 因此,自远程客户端关闭以来,服务器在执行 readByte() 时获取 EOFException . 在 EOFException 的错误处理程序中,它将关闭套接字并打开一个新套接字 .

问题在于:即使在成功打开socket / inputstream / outpustream之后,客户端有时会在 outputStream.write() 调用时获得 SocketWriteError . 它可能与我打开和关闭这些插座的频率有关 . 一个有趣的事情是客户端在破解之前执行任意数量的写入/关闭/重新连接 . 它有时会在第一次重新连接时丢失,有时它会在看到 SocketWriteError 之前重新连接50次 .

这是客户端的错误:

java.net.SocketException: Connection reset by peer: socket write error
       at java.net.SocketOutputStream.socketWrite0(Native Method)
       at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
       at java.net.SocketOutputStream.write(SocketOutputStream.java:115)
       at bytebuffertest.Client.main(Client.java:37)

以下是一些代码片段:

服务器:

public static void main(String[] args)
{
    Server x = new Server();
    x.initialize();
}

private void initialize()
{
    ServerSocket s;
    InputStream is;
    DataInputStream dis;
    while (true) //ADDED THIS!!!!!!!!!!!!!!!!!!!!!!
    {
        try
        {
            s = new ServerSocket(4448);
            s.setSoTimeout(0);
            s.setReuseAddress(true);
            is = s.accept().getInputStream();
            System.out.println("accepted client");
            dis = new DataInputStream(is);
            try
            {

                byte input = dis.readByte();
                System.out.println("read: " + input);
            } catch (Exception ex)
            {
                System.out.println("Exception");
                dis.close();
                is.close();
                s.close();
            }
        } catch (IOException ex)
        {
            System.out.println("ioexception");
        }
    }
}

客户:

public static void main(String[] args)
{
    Socket s;
    OutputStream os;
    try
    {
        s = new Socket("localhost", 4448);
        s.setKeepAlive(true);
        s.setReuseAddress(true);
        os = s.getOutputStream();
        int counter = 0;
        while (true)
        {
            try
            {
                os.write((byte) counter++);
                os.flush();

                os.close();
                s.close();

                s = new Socket("localhost", 4448);
                s.setKeepAlive(true);
                s.setReuseAddress(true);
                os = s.getOutputStream();
            } catch (Exception e)
            {
                e.printStackTrace();
                System.err.println("ERROR: reconnecting...");
            }
        }
    } catch (Exception ex)
    {
        ex.printStackTrace();
        System.err.println("ERROR: could not connect");
    }
}

有谁知道如何正确重新连接?

1 回答

  • 3

    不要在出现错误时关闭ServerSocket,只是.accept()一个新连接 .

    我通常做的是每次ServerSocket.accept()返回一个Socket时,我产生一个线程来处理从该Socket的发送和接收 . 这样,只要有人想要连接到您,您就可以开始接受新连接了 .

相关问题