简体   繁体   English

关于从SocketServer返回的Socket对象

[英]about the returned Socket object from SocketServer

I have a very simple question, however I am confused by a tutorial. 我有一个非常简单的问题,但是我对教程感到困惑。

Say, I create a server & use port 1234: 说,我创建一个服务器并使用端口1234:

ServerSocket server = new ServerSocket(1234);

Then, I ask server to wait for requests by: 然后,我要求服务器通过以下方式等待请求:

while(true) {
  // is the returned socket represents the server side socket or client side socket???
  Socket socket = server.accept();
}

My question is whether the socket returned by server.accept() a server side socket or client side socket? 我的问题是server.accept()返回的套接字是服务器端套接字还是客户端端套接字? It is not very well explained in Java doc . Java doc中对此的解释不是很好。

The reason why I ask this question is because when I run socket.getPort() , it doesn't return server port 1234, instead, it returns a port not defined by me, so, I am thinking it might be the client's socket. 我问这个问题的原因是因为当我运行socket.getPort() ,它没有返回服务器端口1234,而是返回了我未定义的端口,因此,我认为它可能是客户端的套接字。 But I am not sure. 但我不确定。

Listens for a connection to be made to this socket and accepts it. 监听与此套接字建立的连接并接受它。 The method blocks until a connection is made. 该方法将阻塞,直到建立连接为止。

which means, that it is server. 这意味着它是服务器。

socket.getPort() according to javadoc , 根据javadoc的 socket.getPort()

Returns the remote port number to which this socket is connected. 返回此套接字连接到的远程端口号。

A Socket has two ends, where one end will send information to the other end with the OutputStream, and receive information from the other end with the InputStream. 套接字有两个端点,其中一端将通过OutputStream向另一端发送信息,并使用InputStream从另一端接收信息。 See also getInputStream() and getOutputStream() methods on the Socket. 另请参见Socket上的getInputStream()和getOutputStream()方法。

In your terms, you can consider the socket to be server side because the InputStream is receiving information from the client that has connected to the server, and the OutputStream is sending information to the client. 用您的话来说,您可以将套接字视为服务器端,因为InputStream从连接到服务器的客户端接收信息,而OutputStream向客户端发送信息。

Typically once the socket is obtained with the server.accept() method, a thread, created with the socket you obtained, should be used for communicating with the client, so that your server can handle multiple clients at the same time. 通常,一旦通过server.accept()方法获得了套接字,就应该使用通过获得的套接字创建的线程与客户端进行通信,以便服务器可以同时处理多个客户端。

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

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