遇到Java ServerSocket.Accept()问题

时间:2013-12-18 03:20:52

标签: java sockets network-programming serversocket

我一直在使用服务器套接字时遇到问题 我有这两种方法

public boolean sendRequest(String IP, int port) {
    try {
        System.out.println("Inside network send");
        client = new Socket(IP, port);
        DataOutputStream outToClient = new DataOutputStream(
                client.getOutputStream());
        outToClient.writeBytes("Requesting Game\n");
        System.out.println("sent");
        BufferedReader inFromClient = new BufferedReader(
                new InputStreamReader(client.getInputStream()));
        String s = null;
        long start = new Date().getTime();
        while (true) {
            s = inFromClient.readLine();
            if (s != null) {
                if (s.equals("YES"))
                    return true;
                else if (s.equals("NO"))
                    return false;
                else return false;
            }
            long curr = new Date().getTime();
            if((curr-start) > (60*1000))
            {
                System.out.println("TIMEOUT IN receiving request response");
                return false;
            }
            //time out 1 minute
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

public boolean receiveConnection() {
    try {
        System.out.println("Inside network rec");
        server.setSoTimeout(60*1000);
        client = server.accept();
        System.out.println("Rec");
        BufferedReader in = new BufferedReader(new InputStreamReader(
                client.getInputStream()));
        String line;
        long start = new Date().getTime();
        while (true) {
            line = in.readLine();
            if (line != null)
                break;
            long curr = new Date().getTime();
            if((curr-start) > (60*1000))
            {
                System.out.println("TIMEOUT IN receiving connection");
                return false;
            }
            //time out 1 minute
        }
        if (line.equals("Requesting Game")) {
            return true;
        } else
            return false;

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

使用此类构造函数如下

public Communicator() {
    try {
        // initialize a server on this pc
        // connection to other pcs are done on another method
        server = new ServerSocket(1234);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

现在每当我尝试在我的机器上运行此程序时,该服务器使用不同的端口号就可以正常运行

但是当我尝试在不同的机器上播放它并正确连接到它们的IP和端口号时有时会失败 它会使receiveConnection方法陷入server.accept()而另一个方法在创建新Socket(IP,端口)时遇到困难

我需要获得有关此问题的帮助,因为通信必须可靠 感谢

0 个答案:

没有答案