读书人

C# Socket TCP 长连接 服务端如何循环

发布时间: 2012-11-08 08:48:11 作者: rapoo

C# Socket TCP 长连接 服务端怎么循环 接收数据?
如题
我这样写的 但是 一直占资源。

C# code
                while (true)                {                    byte[] buffer = SocketEx.Receive(socketClient, this.BefferSize);                    if (buffer == null)                        continue;                    …………                }


C# code
        public static byte[] Receive(Socket socket, int beffersize)        {            try            {                using (MemoryStream ms = new MemoryStream())                {                    socket.Receive(befferSize, 4, SocketFlags.None);                    int dataLength = BitConverter.ToInt32(befferSize, 0);                    //判断读取字节为0                    if (dataLength == 0)                        return null;                    …………                    …………                    return ms.ToArray();                }            }            catch (Exception ex)            {                throw ex;            }        }


[解决办法]
while (true)还不把cup都占了,如果在主线程,那肯定死了

读书人网 >C#

热点推荐