Java套接字:连接重置

时间:2014-02-18 11:43:41

标签: java android sockets

我已经浏览过,搜索过......并且没有任何东西闪现在我脑海中!

我正在服务器和Android应用之间运行聊天类型的服务。客户端连接,服务器注册套接字,服务器每10分钟向所有连接的设备发送一条消息。

我的问题是随机我有一个连接重置异常。发生问题时我无法追溯。

我的服务器端代码是:

final public class ChatRoomService {
    private final static String AUTHENTICATE = "AUTHENTICATE";
    private final static String BROADCAST = "BROADCAST";
    private final static String DISCONNECT = "DISCONNECT";
    private final static String OK = "OK";
    private final static String NOK = "NK";

    private final static Logger LOGGER = Logger.getLogger(ChatRoomService.class);

    private ServerSocket listener = null;

    @Inject
    private EntityManager entityManager;
    public EntityManager getEntityManager() {
        return entityManager;
    }

    @Inject
    private PlayerManager playerManager;
    PlayerManager getPlayerManager() {
        return playerManager;
    }

    private static HashSet<ChatRoomConnection> connections = new HashSet<ChatRoomConnection>();
    public void addConnection(ChatRoomConnection c) {
        synchronized(connections) {
            connections.add(c);
        }
    }
    public void removeConnection(ChatRoomConnection c) {
        synchronized(connections) {
            connections.remove(c);
        }
    }

    public void startListeningToChatRoomConnection() throws IOException {
        listener = new ServerSocket(9010);

        try {
            LOGGER.infof("startListening - Start listening on port %s", 9010);
            while (true) {
                ChatRoomConnection connection = new ChatRoomConnection(listener.accept(), this);
                addConnection(connection);
                connection.start();
            }
        } catch (IOException e) {
            if (!listener.isClosed())
                LOGGER.errorf("listenToChatRoomConnection - Connection lost during connection: %s", e.getMessage());
        } finally {
            if (listener != null && !listener.isClosed()) {
                LOGGER.infof("listenToChatRoomConnection - Stop listening");
                listener.close();
            }
        }
    }

    public void stopListeningToChatRoomConnection() throws IOException {
        if (!listener.isClosed()) {
            LOGGER.infof("stopListeningToChatRoomConnection - Stop listening");

            listener.close();
            listener = null;

            // Closing all sockets
            for (ChatRoomConnection connection : connections) {
                    connection.close();
            }
            // Clear up the connections list
            synchronized (connections) {
                connections.clear();
            }
        }
    }

    public void broadcastToChatRoomClients(Object message) {
        synchronized (connections) {
            // Log
            LOGGER.debugf("Broadcast ChatRoom: %s - %s", 
                    connections.size(),
                    message.toString());

            for (ChatRoomConnection connection : connections) {
                LOGGER.debugf("Broadcast ChatRoom to %s", connection.userName);
                connection.publish(message);
            }
        }
    }

    private ChatRoomService() {
    }

    private static class ChatRoomConnection extends Thread {
        private Socket socket;
        private BufferedReader readerFromClient;
        private PrintWriter writerToClient;
        public String userName;

        private ChatRoomService chatCService;

        ChatRoomConnection(Socket socket, ChatRoomService chatRoomService) {
            super("ChatRoomConnection");

            this.socket = socket;
            this.chatRoomService = chatRoomService;
        }

        public void run() {
            try {
                readerFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                writerToClient = new PrintWriter(socket.getOutputStream(), true);

                // 1- Authenticate the Device/ Player
                writerToClient.println(ChatRoomService.AUTHENTICATE);   
                writerToClient.flush();
                Gson gson = new Gson();
                Request request = gson.fromJson(readerFromClient.readLine(), Request.class);
                if (chatRoomService.getPlayerManager().isPlayerSignedIn(request.getPlayerId(), request.getSignedInOn())) {
                    Player player = (Player) chatRoomService.getEntityManager().find(Player.class, request.getPlayerId());
                    userName = player.getUsername();
                    LOGGER.infof("listenToChatRoomConnection - Connection established with %s", userName);
                    writerToClient.println(ChatRoomService.OK); 
                    writerToClient.flush();
                    while (true)
                        if ((readerFromClient.readLine() == null) || 
                            (readerFromClient.readLine().startsWith(ChatRoomService.DISCONNECT)))
                        break;
                } else {
                    writerToClient.println(ChatRoomService.NOK);
                    writerToClient.flush();
                }
            } catch (Exception e) {
                LOGGER.errorf("listenToChatRoomConnection - Error with %s: %s", userName, e.getMessage());
                e.printStackTrace();
            } finally {
                try {
                    if (!socket.isClosed()) {
                        LOGGER.infof("listenToChatRoomConnection - Connection closed by the client for %s", userName);
                        socket.close();
                    }
                } catch (IOException e) {
                    LOGGER.errorf("listenToChatRoomConnection - Can not close socket: %s", e.getMessage());
                    e.printStackTrace();
                } finally {
                    chatRoomService.removeConnection(this);
                }
            }
        }

        public void publish(Object message) {
            if (!socket.isClosed()) {
                writerToClient.println(ChatRoomService.BROADCAST);
                Gson gson = new Gson();
                writerToClient.println(gson.toJson(message));
            }
        }

        public void close() {
            writerToClient.println(ChatRoomService.DISCONNECT);
            try {
                LOGGER.infof("listenToChatRoomConnection - Connection closed by the server for %s", userName);
                socket.close();
            } catch (IOException e) {
                LOGGER.errorf("Error when trying to close a socket: %s", e.getMessage());
                e.printStackTrace();
            }
        }
    };
}

设备代码为:

public class ServerBroadcastManager {
    private static final String TAG = ServerBroadcastManager.class.getName();

    // Type of messages from the server
    static public String AUTHENTICATE = "AUTHENTICATE";
    static public String DISCONNECT = "DISCONNECT";
    static public String BROADCAST = "BROADCAST";
    static public String OK = "OK";
    static public String NOK = "NK";

    private int networkPort;
    private ServerBroadcastListener broadcastListener;
    private Socket networkSocket;

    BufferedReader in;
    PrintWriter out;

    public ServerBroadcastManager(Context context, ServerBroadcastListener listener, int port) {
    this.networkPort = port;
    this.broadcastListener = listener;
    }

    public void startListening(final Context context) {
    Runnable run = new Runnable() {
        @Override
        public void run() {
            // Make connection and initialize streams
            try {
                networkSocket = new Socket();
                networkSocket.connect(new InetSocketAddress(mydomain, networkPort), 30*1000);
                in = new BufferedReader(new InputStreamReader(
                        networkSocket.getInputStream()));
                out = new PrintWriter(networkSocket.getOutputStream(), true);

                // Process all messages from server, according to the protocol.
                while (true) {
                    String line = in.readLine();
                    if (line.startsWith(ServerBroadcastManager.AUTHENTICATE)) {
                        Request request = formatAuthenticateRequest(context);
                        Gson requestGson = new Gson();          
                        out.println(requestGson.toJson(request));
                        out.flush();
                        // Waiting for confirmation back
                        line = in.readLine();
                        if (line.startsWith(ServerBroadcastManager.OK)) {
                        } else if (line.startsWith(ServerBroadcastManager.NOK)) {
                        }
                    } else if (line.startsWith(ServerBroadcastManager.BROADCAST)) {
                        Gson gson = new Gson();
                        @SuppressWarnings("unchecked")
                        LinkedHashMap<String,String> broadcast = gson.fromJson(in.readLine(), LinkedHashMap.class);
                        broadcastListener.processBroadcast(broadcast);
                    } else if (line.startsWith(ServerBroadcastManager.DISCONNECT)) {
                        break;
                    }
                }
            } catch (UnknownHostException e) {
                    Log.i(TAG, "Can not resolve hostname");
            } catch (SocketTimeoutException e) {
                    Log.i(TAG, "Connection Timed-out");

                broadcastListener.connectionFailed();
            } catch (IOException e) {
                    Log.i(TAG, "Connection raised on exception: " + e.getMessage());

                if (!networkSocket.isClosed()) {
                    broadcastListener.connectionLost();
                }
            }
        }           
    };

    Thread thread = new Thread(run);
    thread.start();
}

public void stopListening() {
    try {
        if (networkSocket != null)
            networkSocket.close();
    } catch (IOException e) {
            Log.i(TAG, "Exception in stopListening: " + e.getMessage());
    }
}

private Request formatAuthenticateRequest(Context context) {
    Request request = new Request();
    SharedPreferences settings = context.getApplicationContext().getSharedPreferences(Constants.USER_DETAILS, 0);

    request.setPlayerId(BigInteger.valueOf((settings.getLong(Constants.USER_DETAILS_PLAYERID, 0))));
    request.setSignedInOn(settings.getLong(Constants.USER_DETAILS_SIGNEDINON, 0));

    return request;
    }
}

我的最后一招可能是将我的服务器移动到另一个位置,看看这是否与我的宽带路由器无关。我注意到我的一些HTTP呼叫也没有到达服务器,尽管端口转发正确到位。

感谢。 大卫。

1 个答案:

答案 0 :(得分:1)

我无法在源代码中找到服务器每10分钟向所有连接的客户端发送消息的位置,但是在使用持久的WebSocket连接时我遇到了连接重置异常。我通过确保每分钟从客户端发送一些数据(乒乓消息)来解决这个问题。

当我将问题追踪到我的家庭路由器时,它只是在5分钟后关闭所有空闲连接,但防火墙可以表现出同样的行为。在传输数据之前,服务器或客户端都不会注意到关闭的连接。如果客户端期望来自服务器的数据,那么对于客户端来说这尤其令人讨厌 - 数据将永远不会到达。因此,让客户负责检查连接是否仍然有效(并在需要时重新连接)。

自从每分钟从客户端引入乒乓消息以来,我没有看到连接重置异常。