Android Java ServerSocket port number is not what

2019-06-11 14:31发布

问题:

Hi I am doing android development, and found something weird while using socket API.

Between sockets that I created from

ServerSocket server = new ServerSocket(4444);
Socket client = server.accept();

and

client.getPort();

is not 4444.

Since the port number is almost random, the client cannot communicate with server application. Any piece of information or advice will be helpful!

The full sample project is here.

http://vext.eclipselabs.org.codespot.com/files/SocketTest.zip

Thanks in advance!

回答1:

Referenced from Head First Java:



回答2:

When client socket to server socket its will take a random empty port (unused port) on client machine.. but this client should connect to a specific port with server...

When you specify the server socket port; you are listening to this port. and on accept new socket connection you should create a specifice reference for the connected client and continue listening for incoming new connection; and then use this reference to communicate with your client connection.



回答3:

from Java Docs of Socket class public int getPort() Returns the remote port to which this socket is connected. Returns: the remote port number to which this socket is connected, or 0 if the socket is not connected yet.

Try calling getLocalPort()