一种无需使用多线程即可从 Streams 中 Read() 数据的快速方法
我正在开发一个用 C# 编写的在线 FPS,它将使用 P2P 将玩家连接在一起,而不是集中式服务器。我需要一种快速的方法来从每个流中读取数据,然后在收到数据包时通知游戏。
class StreamReader
{
List<XStream> streams;
onPeerFound(XStream stream) {
System.Threading.Thread mthread = new System.Threading.Thread(targetthread);
mthread.start(stream);
}
void targetthread(object sender) {
XStream mstream = (XStream)sender;
while(isrunning) {
byte[] buffer = new byte[4086];
Array.Resize<byte>(ref buffer,mstream.Read(buffer,0,4086));
onPacketReceived.Invoke(buffer,mstream.remoteID);
}
}
}
有没有更快的方法来做到这一点,而无需为每个流创建单独的线程?请注意,每个 XStream 还具有 DataAvailable 属性,该属性返回接收缓冲区中的数据量。
I am working on an online FPS written in C# which will use P2P to connect the players together, instead of a centralized server. I need a fast way to read the data from each stream, and then notify the game when a packet is received.
class StreamReader
{
List<XStream> streams;
onPeerFound(XStream stream) {
System.Threading.Thread mthread = new System.Threading.Thread(targetthread);
mthread.start(stream);
}
void targetthread(object sender) {
XStream mstream = (XStream)sender;
while(isrunning) {
byte[] buffer = new byte[4086];
Array.Resize<byte>(ref buffer,mstream.Read(buffer,0,4086));
onPacketReceived.Invoke(buffer,mstream.remoteID);
}
}
}
Is there a faster way to do this without creating a separate thread for each stream? Note that each XStream also has a DataAvailable property, which returns the amount of data in the receive buffer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用异步IO?您调用 BeginRead,而不是 Read,然后在线程池线程上进行回调。它仍然是线程化的,但您不必管理线程,并且它通常比每个请求的线程更有效。
顺便说一句, Array.Resize 很可怕......这很可能会进行内存复制,除非必须这样做,否则您不想这样做。相反,您应该读入固定大小的缓冲区,并具有在更高级别处理片段或短消息的逻辑。
Use async IO? instead of Read you call BeginRead and then get a call back on a thread pool thread. Its still threaded but you don't have to manage the threads and its usually more efficient than thread per request.
That Array.Resize is scary by the way... thats going to most likely do a memcopy which you don't want to do unless you have to. Instead you should be reading into a fixed size buffer and have the logic to deal with fragments or short messages at a higher level.