0

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!

user1165390
  • 71
  • 1
  • 5
  • How is this android? If you rn this on a phone you will get a BindAddress Error. – JPM Mar 29 '12 at 21:27
  • *Non sequitur.* The client port number is indeed almost random, but it doesn't follow hat the client can't communicate with the server. That's how TCP works. Obviously the server knows the client port, and IP address too. There is no problem here to solve. – user207421 Jan 19 '16 at 01:03

3 Answers3

5

Referenced from Head First Java:

enter image description here

yorkw
  • 40,926
  • 10
  • 117
  • 130
0

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.

Mohammad Shraim
  • 1,173
  • 12
  • 21
0

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()

JProgrammer
  • 1,135
  • 1
  • 10
  • 27