简体   繁体   English

客户端服务器应用java

[英]Client server application java

I learned that Server application makes a ServerSocket in a specific port, 我了解到Server应用程序在特定端口中创建了一个ServerSocket,

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. 所以客户端知道服务器的IP地址和端口,我很困惑服务器如何以及何时获得有关客户端的知识。 Please help. 请帮忙。

Thanx in advance !!! Thanx提前!!!

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. 因此,当服务器应用程序执行serverSock.accept()时,它实际上会阻塞并等待客户端到达。

Once a client tries to connect, the accept() method will unblock itself and return another Socket instance, this time representing the client. 一旦客户端尝试连接, accept()方法将取消阻塞自身并返回另一个Socket实例,这次代表客户端。

Through that new Socket instance you can then know who the client is. 通过这个新的Socket实例,您可以知道客户端是谁。 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());

The server accepts the client with ServerSock.accept() . 服务器使用ServerSock.accept()接受客户端。 Here is a tutorial. 是一个教程。

Well, the client knows the IP and port of the server to connect. 那么,客户端知道要连接的服务器的IP和端口。
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. 为此,将为客户端进程分配一个ephimeral端口,以便如果服务器的TCP层接受请求连接(服务器正在侦听并尝试接受连接),则服务器可以使用客户端套接字。客户端的IP和端口。
So now server nows how to reach back the client. 所以现在服务器如何回到客户端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM