如何处理套接字程序

时间:2015-10-21 13:09:17

标签: java sockets error-handling

我写了一个下面给出的程序。它接受来自客户端的一些数据。回应成功。有时会抛出连接重置错误&由于某些套接字连接保持未关闭的结果。任何想法如何在客户端代码尝试通信时处理连接重置错误&客户端自动关闭连接?

import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class tcp_server implements Runnable {

    private final Socket server;
    private PrintWriter toClient = null;
    private BufferedReader fromClient = null;

    public tcp_server(Socket s) {
        this.server = s;
    }

    @Override
    public void run() {
        String name = "";
        synchronized (server) {
            try {
                server.setSoTimeout(6000);
                toClient
                        = new PrintWriter(server.getOutputStream(), true);
                fromClient
                        = new BufferedReader(
                                new InputStreamReader(server.getInputStream()));
                String line = "";
                String data = "";
                while ((line = fromClient.readLine()) != null) {
                    data = data + line;
                    toClient.println("{status:success}");
                    break;
                }
            } catch (Exception eb) {

                System.out.println("{status:error,Reason:" + eb.getMessage() + "}");
            } finally {
                // System.out.println("Finally not called if timeout occurs");
                if (toClient != null) {                    
                    toClient.close();
                }
                if (fromClient != null) {
                    try {                        
                        fromClient.close();
                    } catch (IOException ex) {
                        Logger.getLogger(tcp_server.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                try {
                  server.close();                    
                } catch (IOException ex) {
                    Logger.getLogger(tcp_server.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        int serverPort = 40820;
        ServerSocket serverSocket = new ServerSocket(serverPort);
        synchronized (serverSocket) {
            for (;;) {
                Socket server = serverSocket.accept();
                new Thread(new tcp_server(server)).start();
            }
        }
    }
}

这是更好的代码...但仍然有相同的错误"连接重置"虽然应用超时到60秒

1 个答案:

答案 0 :(得分:2)

当然,你通过关闭连接来处理

真正的问题是你为什么得到它?有几个常见原因:

  • 您写入了已被对等方关闭的连接
  • 您关闭了连接而没有读取已经到达套接字接收缓冲区的数据。这将重置同伴。

这两个都是应该修复的应用程序协议错误。发送无法读取的数据没有任何意义。