调用 Socket.Receive 时防止线程休眠
我正在开发一个低延迟的金融应用程序,该应用程序通过套接字接收 tcp 数据。
这就是我建立套接字连接并接收字节的方式:
public class IncomingData
{
Socket _Socket;
byte[] buffer = new byte[4096];
public static void Connect(IPEndPoint endPoint)
{
_Socket = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
_Socket.Connect(endPoint);
}
public static void ReadSocket(int ReadQty)
{
_Socket.Receive(buffer, 0, ReadQty, SocketFlags.None);
}
}
我听说当您在 Stream 套接字上调用 Receive() 时,调用线程将进入睡眠状态,并且在以下情况下被唤醒:收到数据。我希望线程全速运行(使用 CPU 容量)。
有没有办法使用 Stream 套接字来做到这一点?如果唯一的方法是使用原始套接字,您能提供一个示例吗?
I'm working on a low latency financial application that receives tcp data over sockets.
This is how I'm making a socket connection and receiving bytes:
public class IncomingData
{
Socket _Socket;
byte[] buffer = new byte[4096];
public static void Connect(IPEndPoint endPoint)
{
_Socket = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
_Socket.Connect(endPoint);
}
public static void ReadSocket(int ReadQty)
{
_Socket.Receive(buffer, 0, ReadQty, SocketFlags.None);
}
}
I heard that when you call Receive()
on a Stream socket, that the calling thread is put to sleep, and it is woken up when data is received. I would like the thread to be running at full speed (using CPU capacity).
Is there a way I can do this using a Stream socket? If the only way is with a Raw socket, could you provide an example?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果我理解正确的话,您希望 Receive 不被阻止?
看一下套接字类的
BeginX
/EndX
方法。这些方法异步执行(不会阻塞当前线程)。它们接受回调方法作为参数之一,并且在操作完成时将调用该方法(在本例中,将接收数据)。它本质上与事件相同。If I understand you correctly, you want Receive to not block?
Take a look at the
BeginX
/EndX
methods of the socket class. These methods perform asynchronously (not blocking on the current thread). They accept a callback method as one of their parameters and that method will be called when the operation completes (in this case, data would be received). It is essentially the same as events.您可以使用 Socket.Poll 来确定套接字是否有数据,否则继续旋转:
You can use
Socket.Poll
to determine if the socket has data and keep spinning otherwise:也许可以通过查看 networkComms.net 来回避通过网络发送数据的整个问题,特别是演示最基本功能的简短示例此处,希望不会过于复杂!您可能遇到的大多数问题都已得到解决,这可能会节省您一些时间。
Perhaps side step the whole problem of sending data over a network by checking out networkComms.net and in particular the short example demonstrating the most basic functionality here, hopefully not overly complex! Most of the problems you might come across will already have been solved and it might save you some time.