Java Socket 和 ServerSocket 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2004531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:22:33  来源:igfitidea点击:

What is the difference between Socket and ServerSocket?

javasocketsserversocket

提问by sevugarajan

If Socketrepresents client side and ServerSocketrepresents server side, why Socket.readreads the data from server side? I'm really confused, Can you please clarify it to me?

如果Socket代表客户端,ServerSocket代表服务器端,为什么Socket.read要从服务器端读取数据?我真的很困惑,你能帮我澄清一下吗?

回答by Noon Silk

Because it's reading what has been sent to you bythe server.

因为它是阅读的内容已经发送到你服务器。

回答by ArunDhaJ

ServerSocket is again a Socket with additional features of server endpoint. The server features includes listening to the port and accepting an incoming connection etc...

ServerSocket 又是一个具有服务器端点附加功能的 Socket。服务器功能包括侦听端口和接受传入连接等...

回答by OscarRyz

why socket.read reads the data from serverside

为什么 socket.read 从服务器端读取数据

Because it is reading the data sentby the server through the network, it is not reading directly the server filesystem or resouces ( db , ram or anything like that ) it is reading the data that was already processed by the ServerSocket.

因为它正在读取服务器通过网络发送的数据,它不是直接读取服务器文件系统或资源(db、ram 或类似的东西),而是读取已经由 ServerSocket 处理的数据。

Think about the Socket as your web browser and the ServerSocket as the remote webserver.

将 Socket 视为您的 Web 浏览器,将 ServerSocket 视为远程 Web 服务器。

When you request an image, page, etc, the webserver ( The ServerSocket ) writes the bytes to the client, in turn the client has to read them ( to know what the webserver sent right? ) and process them by displaying them to the final user.

当您请求图像、页面等时,网络服务器( The ServerSocket )将字节写入客户端,反过来客户端必须读取它们(以了解网络服务器正确发送了什么?)并通过将它们显示到最后来处理它们用户。

The same happend with ServerSocket/Socket but at a lower level. The socket readsinformation from the ServerSocket.

ServerSocket/Socket 也发生了同样的情况,但发生在较低级别。套接字从 ServerSocket读取信息。

Does it make sense?

是否有意义?

回答by Sunil Kumar Sahoo

Socketis for the client side and ServerSocketis for the server side.

Socket用于客户端,ServerSocket用于服务器端。

回答by Marc Juchli

java.net.ServerSocket

java.net.ServerSocket

This class implements server sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester.

此类实现服务器套接字。服务器套接字等待通过网络传入的请求。它根据该请求执行一些操作,然后可能将结果返回给请求者。

java.net.Socket

套接字

This class implements client sockets (also called just "sockets"). A socket is an endpoint for communication between two machines.

此类实现客户端套接字(也称为“套接字”)。套接字是两台机器之间通信的端点。

回答by smwikipedia

(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

http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html

Admittedly, when carrying out TCP/IP communication, all the necessary information can be provided by the Socketclass alone for the sole purpose of communication. No matter it is on server side or client side.

诚然,在进行 TCP/IP 通信时,所有必要的信息都可以由Socket类单独提供,仅用于通信目的。无论是在服务器端还是客户端。

As you can see from the above link, server sideuse the following code to acquire its own Socketinstance. That is, anothersocket is created on the same server local port and the client port pair.

从上面的链接可以看出,服务器端使用下面的代码来获取自己的Socket实例。也就是说,在相同的服务器本地端口和客户端端口对上创建另一个套接字。

enter image description here

在此处输入图片说明

Then, server use this Socketinstance to talk to the client.

然后,服务器使用此Socket实例与客户端对话。

And to make the picture complete, below code snippet shows client's Socketinstance.

为了使图片完整,下面的代码片段显示了客户端Socket实例。

enter image description here

在此处输入图片说明

So if Socketcan do it all already, why do we still need the ServerSocket?

那么如果Socket已经可以做到这一切,为什么我们还需要ServerSocket

This is because of the working paradigm of communication over TCP/IP protocol.

这是因为通过 TCP/IP 协议进行通信的工作范式。

When 2 programs talk over TCP/IP, usually one will passivelylisten/wait on a <IP:port>and the other one will activelyconnect to it.

当两个程序通过 TCP/IP 通信时,通常一个会被动地监听/等待一个<IP:port>,另一个会主动连接到它。

So you can see, at this very starting phaseof the communication, the 2 sides have very different behaviors. So 2 different classes are used to reflect this difference.

所以你可以看到,在这次starting phase交流中,双方的行为非常不同。因此使用 2 个不同的类来反映这种差异。

  • Socketclass encapsulates the behavior of the active side. (a.k.a. the client)
  • ServerSocketclass encapsulates the behavior of the passive side (a.k.a. the server)
  • Socket类封装了主动端的行为。(又名客户)
  • ServerSocket类封装了被动端(又名服务器)的行为

Once the ServerSocketaccomplished its listening task and detectedan incoming connection, it will accept()it and create a new Socketinstance to facilitate the communication.

一旦ServerSocket完成其侦听任务和detected传入连接,它将accept()创建一个新Socket实例以促进通信。

Similarily, in java.niopackage, you will find ServerSocketChanneland SocketChannelclasses. And still, they behave like this:

同样,在java.nio包中,你会发现ServerSocketChannelSocketChannel类。而且,他们的行为是这样的:

ServerSocketChannel -------------> SocketChannel
                      accept()

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.

因此,在某种程度上,我同意 @JohnK 在评论中指出的it's more or less just a 6-letter difference

回答by SuppieRK

First of all, let's clarify what IS Socketlook like: in a common case, Socketis a concatenation of IP and port via :, for example: 127.0.0.1:8080.

首先,让我们澄清一下 IS 是Socket什么样的:在常见情况下,Socket是 IP 和端口 via 的串联:,例如:127.0.0.1:8080

So, you decided to make client-server application using Socket. There's nothing too much complicated. Here's short explanation about making connection between clientand server:

因此,您决定使用Socket. 没有什么太复杂的。以下是关于在client和之间建立连接的简短说明server

  1. First of all, let's clarify that fact, that our clienthave his own Socketand knows serverIP address and port. For serverthere are provided only ServerSocketand port. In both cases port are the same number between 0 and 65535.
  2. So, we decided to connect our clientto our server:

    • clientcreates his Socket clientSocketobject with known IP and port of our server.

    • servergot incoming connection request with his ServerSocket.accept()method, which generates new Socket newClientSocketobject (still on a serverside (!) ).

    • Further data exchanging goes via clientSocketand newClientSocketobjects (not between clientSocketand ServerSocket).

  1. 首先,让我们澄清这一事实,我们client有自己的Socket和知道server的IP地址和端口。因为server只提供了ServerSocket和端口。在这两种情况下,端口都是 0 到 65535 之间的相同数字。
  2. 所以,我们决定将我们的连接client到我们的server

    • clientSocket clientSocket使用我们的已知 IP 和端口创建他的对象server

    • server使用他的ServerSocket.accept()方法获得传入的连接请求,该方法生成新Socket newClientSocket对象(仍在server一边 (!) )。

    • 进一步的数据交换通过clientSocketnewClientSocket对象(而不是在clientSocket和之间ServerSocket)。

Hereis almost perfect picture to understand the basic connection process (keep in mind, that Socketobject on Clientat this picture - same objects).

这里几乎是完美的画面,了解基本的连接过程(记住,该Socket物体Client在这幅画-相同的对象)。

After you've made this simple structure, you need to open two streams on both Client.clientSocketand Server.newClientSocketsides for reading and writing information.

你做这个简单的结构之后,你需要打开两个两个流Client.clientSocketServer.newClientSocket两侧的读取和写入信息。

回答by pgcool

ServerSocketis created to bindto a port and listenfor a connectfrom a client. So, a server just waits for a conversation and doesn't start one.

ServerSocket被创建到bind一个端口和listen一个connect来自客户端。因此,服务器只等待对话而不启动对话。

ClientSocketis created to connectto a listening server. The client initiates the connection.

ClientSocket创建于connectlistenING服务器。客户端发起连接。

Example: Think of an inbound call center as an example. These services are servers. They don't initiate a call but wait for a call to come in from clients. Once the calls are in, they can engage in a two way conversation.

示例:以呼入呼叫中心为例。这些服务是服务器。他们不发起呼叫,而是等待来自客户的呼叫。一旦呼叫进入,他们就可以进行双向对话。