Socket和ServerSocket有什么区别? [英] What is the difference between Socket and ServerSocket?
问题描述
如果 Socket
代表客户端而 ServerSocket
代表服务器端,为什么 Socket.read
从服务器端读取数据?我真的很困惑,请你澄清一下吗?
If Socket
represents client side and ServerSocket
represents server side, why Socket.read
reads the data from server side? I'm really confused, Can you please clarify it to me?
推荐答案
(我发布这个答案是因为我觉得这很重要使逻辑正确。)
(I post this answer because I always feel it's important to make the logic right.)
我建议你看看下面的例子。
I suggest you take a look at the following sample.
http://docs.oracle.com/javase/tutorial/networking/sockets/ clientServer.html
不可否认,在进行TCP / IP通信时,所有必要的信息都可以通过 Socket提供
仅为了沟通而单独上课。无论是在服务器端还是客户端。
Admittedly, when carrying out TCP/IP communication, all the necessary information can be provided by the Socket
class alone for the sole purpose of communication. No matter it is on server side or client side.
从上面的链接可以看出,服务器端使用以下代码获取自己的 Socket
实例。也就是说,另一个套接字是在另一个端口上创建的。
As you can see from the above link, server side use the following code to acquire its own Socket
instance. That is, another socket is created on another port.
然后,服务器使用此套接字
与客户交谈的实例。
Then, server use this Socket
instance to talk to the client.
为了使图片完整,下面的代码片段显示 clien t 套接字
实例。
And to make the picture complete, below code snippet shows client's Socket
instance.
因此,如果 Socket
已经可以完成所有工作,为什么我们呢还需要 ServerSocket
?
So if Socket
can do it all already, why do we still need the ServerSocket
?
这是因为通过TCP / IP进行通信的工作范例协议。
This is because of the working paradigm of communication over TCP/IP protocol.
当2个程序通过TCP / IP进行通话时,通常会有一个被动地监听/等待< IP:端口>
,另一个主动连接到它。
When 2 programs talk over TCP/IP, usually one will passively listen/wait on a <IP:port>
and the other one will actively connect to it.
所以你可以看到,在这个非常的开始阶段
的沟通中,双方都非常不同的行为。因此,使用2个不同的类来反映这种差异。
So you can see, at this very starting phase
of the communication, the 2 sides have very different behaviors. So 2 different classes are used to reflect this difference.
-
Socket
class封装了活动方的行为。 (又称客户端) -
ServerSocket
类封装了被动方(也就是服务器)的行为
Socket
class encapsulates the behavior of the active side. (a.k.a. the client)ServerSocket
class encapsulates the behavior of the passive side (a.k.a. the server)
ServerSocket
完成其侦听任务并检测到
传入连接,它将 accept()
它并创建一个新的 Socket
实例以方便通信。
Once the ServerSocket
accomplished its listening task and detected
an incoming connection, it will accept()
it and create a new Socket
instance to facilitate the communication.
类似地,在 java.nio
包中,你会发现 ServerSocketChannel
和 SocketChannel
类。而且,它们的行为如下:
Similarily, in java.nio
package, you will find ServerSocketChannel
and SocketChannel
classes. And still, they behave like this:
ServerSocketChannel -------------> SocketChannel
accept()
所以,在某种程度上,我同意@JohnK的观点在评论中指出,它或多或少只是一个6个字母的差异
。
So, to some extent, I agree with @JohnK as he pointed out in the comment, it's more or less just a 6-letter difference
.
这篇关于Socket和ServerSocket有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!