如何同步读取和写入套接字? [英] How the reading from and writing to sockets are synchronized?

查看:117
本文介绍了如何同步读取和写入套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们创建一个套接字。在套接字的一侧,我们有一个服务器,另一边有一个客户端。服务器和客户端都可以写入和读取套接字。这是我的理解。我不明白以下事项:

We create a socket. On one side of the socket we have a "server" and on another side there is a "client". Both, the server and client, can write to and read from the socket. It is what i understand. I do not understand the following things:


  1. 如果服务器从套接字读取,它是否只在套接字中看到那些东西哪个被客户端写入套接字?我的意思是如果服务器向套接字写入内容而不是从套接字读取,它(服务器)是否会在套接字中看到它(服务器)在那里写的内容?我希望不会。

  1. If a server reads from the socket, does it see in the socket only those stuff which was written to the socket by the client? I mean if server writes something to the socket and than reads from the socket, will it (server) see in the socket the stuff it (server) wrote there? I hope not.

让我们考虑以下情况。客户端向套接字写入内容,然后将新内容写入套接字,然后服务器从套接字读取。服务器会在那里看到什么?只有客户编写的新内容或新和旧内容?

Let's consider the following situation. A client write something to the socket and then it writes something new to the socket and then server reads from the socket. What will the server see there? Only the "new" stuff written by the client or both "new" and "old" one?

如果客户端(或服务器)写入套接字,它能否看到其他方面是否收到了书面信息?例如 out.println(Hello,Server!)将返回 true 服务器收到此消息。

If a client (or server) writes to the socket, can it see if the written information was received by other side? For example out.println("Hello, Server!") will return true it server received this message.


推荐答案

套接字连接代表两个单向流:一个从客户端到服务器从服务器到客户端。

A socket connection represents two unidirectional streams: one from the client to the server and one from the server to the client.

每一方都可以将数据放入一个流并从另一个流中读取。

Each side can put data into one stream and read from the other.

将放入一个流的数据附加到已存在的数据的末尾。

Data put into one stream is appended to the end of the data thats already there.

从流的一端读取数据时,可用的最旧数据将被读取(即它是一个流是一个FIFO)。

When data is read from one end of the stream, the oldest data available will be read (i.e. it a stream is a FIFO).

这些语句可以让你回答所有问题,但我也会明确说明:

These statements should enable you to answer all your questions, but I'll make it explicit as well:


  1. 服务器只读取客户写的内容,而不是自己编写的内容

  2. 服务器将首先阅读旧的东西,然后是新的东西

  3. 客户没有直接的方法知道是否数据实际上是由另一方接收的,除非服务器发送响应的内容。在某些情况下,它可以知道发送是否失败(例如,当客户端存在物理问题时),但通常不能依赖该通知。

这篇关于如何同步读取和写入套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆