客户端服务器应用程序java

发布于 2024-10-10 00:17:57 字数 284 浏览 0 评论 0原文

我了解到服务器应用程序在特定端口中创建 ServerSocket,

ServerSocket ServerSock=new ServerSocket(9000);

客户端与服务器应用程序建立套接字连接,

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

因此客户端知道服务器的 IP 地址和端口,我很困惑服务器如何以及何时获取有关客户端的信息。请帮忙。

提前谢谢!

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 !!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

七七 2024-10-17 00:17:57

服务器正在“监听”来自客户端的传入连接。想象一下端口号就是门号,服务器正在门口等待客人。

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

一旦客户端尝试连接,接受() 方法将解锁自身并返回另一个 Socket 实例,这次代表客户端。

通过这个新的 Socket 实例,您可以知道客户端是谁。服务器应用程序代码的示例如下:

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 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());
小嗷兮 2024-10-17 00:17:57

服务器通过ServerSock.accept()接受客户端。 这里是一个教程。

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

画中仙 2024-10-17 00:17:57

好了,客户端知道要连接的服务器的 IP 和端口。
然后客户端尝试与服务器连接。
为此,将向客户端进程分配一个临时端口,以便如果服务器(服务器正在侦听并尝试接受连接)机器的 TCP 层接受请求连接,则客户端套接字将可供服务器使用客户端的IP和端口。
现在服务器现在如何联系客户端。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文