C#创建多个TCP连接,然后等待数据 [英] Create multiple TCP Connections in C# then wait for data

查看:723
本文介绍了C#创建多个TCP连接,然后等待数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在创建一个Windows服务,将创建到多台计算机的TCP连接(所有机器上的同一个插座),然后监听来自这些机器'事件'。我试图编写代码来创建一个连接,然后产卵侦听从机器等待数据包的连接线,然后解码该来通过数据包,并要求根据数据包的有效载荷功能。

I am currently creating a Windows Service that will create TCP connections to multiple machines (same socket on all machines) and then listen for 'events' from those machines. I am attempting to write the code to create a connection and then spawn a thread that listens to the connection waiting for packets from the machine, then decode the packets that come through, and call a function depending on the payload of the packet.

但问题是我不完全知道怎么做,在C#。没有人有任何有益的建议或链接,可以帮助我做到这一点?

The problem is I'm not entirely sure how to do that in C#. Does anyone have any helpful suggestions or links that might help me do this?

在此先感谢您的帮助!

推荐答案

您可以异步接收每一个socket连接,并解码从其他机器来执行任务中的数据(你可以找到有关异步方法这里一些有用的信息:的 http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx

You can have asynchronous receive for every socket connection and decode the data coming from other machines to perform your tasks (You can find some useful information about asynchronous methods here: http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx).

要创建连接,你可以这样做:

To create a connection, you can do:

Socket sock = Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(new IPEndPoint(address, port));



同样的方式,你可以创建多个连接,并保持在词典列表有引用(无论你喜欢)

Same way you can create multiple connections and keep there references in a List of Dictionary (whichever you prefer).

有关异步接收套接字上的数据,你可以这样做:

For receiving data asynchronously on a socket, you can do:

sock.BeginReceive(buffer, 0, buffer.len, SocketFlags.None, new AsyncCallback(OnDataReceived), null);



该方法 OnDataReceived 将被调用时收到。操作完成

The method OnDataReceived will be called when receive operation completes.

OnDataReceived 方法,你必须做的:

void OnDataReceived(IAsyncResult result)
{
   int dataReceived = sock.EndReceive(result);
   //Make sure that dataReceived is equal to amount of data you wanted to receive. If it is
   //less then the data you wanted, you can do synchronous receive to read remaining data.

  //When all of the data is recieved, call BeginReceive again to receive more data


  //... Do your decoding and call the method ...//
}

我希望这可以帮助你。

这篇关于C#创建多个TCP连接,然后等待数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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