客户端服务器应用程序java

问题描述:

我了解到Server应用程序在特定端口中创建一个ServerSocket,

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");

因此,客户端知道服务器的IP地址和端口,获得有关客户端的知识。请帮助。

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

服务器正在侦听来自客户端的传入连接。想象一下,端口号是门的号码,服务器正在门口等候客人。

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.

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

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

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

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

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

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