我想提出一个原型客户端和服务器,这样我可以了解如何处理重新连接。 服务器应该创建一个ServerSocket和听下去。客户端可以连接,发送它的数据,并关闭其插槽,但它不会发出“我已完成和关闭”类型的消息到服务器。出于这个原因,服务器获取EOFException当它一readByte()因为远程客户端已关闭。在为EOFException错误处理程序,它会关闭套接字并打开一个新的。

下面的问题:客户端有时会当它的SocketWriteError调用它成功地打开插座/的InputStream / outpustream即使经过outputStream.write()。它可能有一些做与我打开和关闭这些插座的频率。一个有趣的事情是,客户确实/关闭/ crapping之前坠崖写入任意数量。它有时会废话了在第一重新连接,其他时间它将采取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)

下面是一些代码片段:

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上的误差,只是。接受()的新连接。

我通常做是每次的ServerSocket.accept()返回一个插座,我产卵关闭一个线程来处理发送,并从该插座接收。这样,你就可以开始,只要有人想连接到你接受一个新的连接。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top