开发者

A fast way to Read() data from Streams without using multiple threads

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 stre开发者_如何学JAVAam, 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜