如何:同时发送和接收数据包 [英] How To : Send and receive packet simultaneously

查看:78
本文介绍了如何:同时发送和接收数据包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的朋友们,

我正在使用VS开发TCP套接字通信程序。 C#。

在服务器端,我使用一个套接字来接受客户端。在线程函数中,我调用Socket.Receive,另一方面,我想使用相同的套接字将数据发送到客户端。

但是在接收时发送数据时发生了错误。好像说连接被远程主机强行关闭。

请帮帮我。

谢谢。

Dear friends,
I am developing a TCP socket communication program using VS. C#.
At the server side, I use one socket to accept a client. In thread function, I call Socket.Receive and on the other hand I want to send data to the client using same socket.
But when send data while receiving, an error occured. It seems to say that connection is closed forcibly by the remote host.
Please help me.
Thanks.

推荐答案



客户端或服务器都不知道正在交换多少数据。并且,如果在另一个读取最后一条消息之前断开连接,则连接将丢失,从而导致您观察到的错误。


Neither the client or the server has any idea how much data is being exchanged. And, if one disconnects before the other has read the last message, the connection will be lost causing the error you are observing.



以下是对你能做什么的想法:


Here's a thought on what you can do:



  • 使用同步客户端/服务器。

  • 定义消息协议:



    • 有客户端发送GO消息,如< GO />。

    • 等待服务器响应OK消息,如< OK />。这表示服务器即将发送字节。

    • 服务器使用诸如< DATA>数据块< / DATA>之类的消息发送字节。

    • 当客户端收到字节时,客户端响应OK消息(< OK />)。服务器在发送下一个数据块之前等待客户端的OK消息。

    • 当服务器发送最后一块数据并收到客户端的OK消息时,服务器发送完成消息,如< FINISHED /> ;.

    • 服务器等待客户端以< OK />响应。这表明服务器可以断开连接。

    • 现在您可以关闭客户端的连接。



    你几乎无法控制缓冲区的大小,所以你可能需要确保在消息中正确识别两个或多个数据缓冲区。


    You have very little control over the size of the buffers, so you may need to insure that two or more data buffers are properly identified in a message.



    希望帮助。


    Hope that helps.


    这篇关于如何:同时发送和接收数据包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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