我正在制作原型客户端和服务器,以便可以了解如何处理重新连接。
服务器应该创建一个服务器套接字并永远监听。客户端可以连接,发送其数据并关闭其套接字,但不会向服务器发送“我完成并关闭”类型的消息。因此,由于远程客户端已关闭,服务器在执行EOFException时将获得readByte()。在EOFException的错误处理程序中,它将关闭套接字并打开一个新套接字。

这是问题所在:即使成功打开套接字/输入流/输出流,客户端有时也会在调用SocketWriteError时获得outputStream.write()。这可能与我打开和关闭这些插座的频率有关。一件有趣的事是,客户端在淘汰之前会进行任意数量的写入/关闭/重新连接。有时,它会在第一次重新连接时出现故障,而其他时候,需要50次重新连接才能看到SocketWriteError

这是客户端的错误:

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)

Here are some snippets of code:

SERVER:

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");
    }
}


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

最佳答案

不要在发生错误时关闭ServerSocket,只需.accept()一个新连接即可。

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

08-06 06:52
查看更多