【发布时间】:2015-05-20 12:40:20
【问题描述】:
我尝试 TCP 打孔的另一个障碍。 我的服务器位于 NAT 后面,我正在循环调用 socket.connect() 到手机的 NAT 后公共 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
【问题讨论】:
标签: java sockets tcp serversocket