Socket.connect()连接但没有serverSocket监听

时间:2015-05-20 12:40:20

标签: java sockets tcp serversocket

我尝试TCP打孔的另一个障碍。 我的服务器坐在NAT后面,我正在调用socket.connect()到手机的NAT'd公共IP。

在我的手机上,我按一个按钮,运行socket.connect()到服务器的NAT'd公共IP。手机说它连接到服务器的公共IP和端口。但服务器似乎没有意识到这一点。

如果我在服务器上运行serverSocket而不是socket.connect(),则手机无法连接。

这令我感到困惑。如果没有serverSocket监听,为什么移动电话会调用socket.connect()成功?

任何帮助都将不胜感激。

这是手机应用程序上的代码。

try {
        Log.d("stop", "line 64");

        Log.d("stop", "line");
        Log.d("localHost: ", myIPAddress.getHostAddress());
        Socket clientSocket = new Socket();
        Log.d("stop", "line 70");
        clientSocket.setReuseAddress(true);
        clientSocket.bind(new InetSocketAddress(myIPAddress.getHostAddress(), myPort));
        Log.d("stop", "line 72");
        clientSocket.connect(new InetSocketAddress(serverIPAddress.getHostAddress(), serverPort), 15000);
        Log.d("connected", clientSocket.toString());



        //BufferedReader inFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
        //receivedMessage = inFromClient.readLine();
        Log.d("stop", "line 78");


        //globalSocket app = (globalSocket)getApplication();
        //app.setSocket(clientSocket);
        commsock = clientSocket;

    } catch (IOException e) {

        //Toast.makeText(this, "socket caughyt", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
        error1 = "no Server";
        Log.d("error", error1 + e.getMessage());

    }

这是我服务器应用程序代码的整个循环。

    while(true){

        Thread.sleep(5000);
        try {

                System.out.println("105");
                mobileSocket2 = new Socket();
                mobileSocket2.setReuseAddress(true);
                System.out.println("109");
                //mobileSocket.setReusePort(true);
                //mobileSocket2.setSoTimeout(50);

                mobileSocket2.bind(new InetSocketAddress(myIPAddress.getHostAddress(), myPort));
                System.out.println("bound");

                }
                catch (Exception e) {

                    System.out.println("caught 104: " + e.toString());
                }


        try{

                System.out.println("124");
                System.out.println("connection made 29: " + mobileSocket2);
                mobileSocket2.connect(new InetSocketAddress(mobileAddress.getHostAddress(), mobilePort),5000);
                System.out.println("connection made 239: " + mobileSocket2);



            }
            catch(Exception e){
                System.out.println("exception 2 caught " + e.toString());
                mobileSocket2.close();


            }



    //}//end of while   
} // end of main

1 个答案:

答案 0 :(得分:0)

为什么不在服务器代码中使用接受方法: http://docs.oracle.com/javase/7/docs/api/java/net/ServerSocket.html#accept%28%29