Client server application java

时光毁灭记忆、已成空白 提交于 2019-12-10 20:41:09

问题


I learned that Server application makes a ServerSocket in a specific port,

ServerSocket ServerSock=new ServerSocket(9000);

and client makes a socket connection to the server application,

Socket sock=new Socket("127.0.0.1","9000");

So client knows the Ip address and port of the server, I'm confused how and when the server gets knowledge about the client. Please help.

Thanx in advance !!!


回答1:


The Server is 'listening' for incoming connections from clients. Just imagine the port number as being the door number and the server is waiting at that door for guests.

So when the server application does serverSock.accept() it in fact blocks and waits for clients to arrive.

Once a client tries to connect, the accept() method will unblock itself and return another Socket instance, this time representing the client.

Through that new Socket instance you can then know who the client is. An example of your server's application code would be:

ServerSocket serverSock=new ServerSocket(9000);

Socket clientSock = serverSock.accept(); //this will wait for a client

System.out.println("Yay we have a guest! He's coming from " + clientSock.getInetAddress());



回答2:


The server accepts the client with ServerSock.accept(). Here is a tutorial.




回答3:


Well, the client knows the IP and port of the server to connect.
The client then tries to connect with the server.
For this, an ephimeral port will be assigned to the client process so that if the request connection is accepted by the TCP layer of the server's (server is listening and trying to accept connections) machine a client socket will be available to the server with the IP and port of the client.
So now server nows how to reach back the client.



来源:https://stackoverflow.com/questions/4578476/client-server-application-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!