C#如何实现用socket建立并发服务器模型?

本文介绍了一个基于C#的Socket并发服务器模型的初步设计思路。通过客户端代码示例展示了连接、接收及发送数据的过程,并寻求服务器端的设计建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C#如何实现用socket建立并发服务器模型?
最近在做一个用socket建立并发服务器的模型,平台是C#,在建立服务器时考虑到利用线程池,异步操作。但是现在无从下手?
客户端的代码已经写出来了,具体如下:
ContractedBlock.gifExpandedBlockStart.gifCode
public void StartClient()
        {
            
try
            {
                IPHostEntry ipHostInfo 
= Dns.Resolve(ip);
                IPAddress ipAddress 
= ipHostInfo.AddressList[0];
                IPEndPoint remoteEP 
= new IPEndPoint(ipAddress, port);

                
// Create a TCP/IP socket.
                socket = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream, ProtocolType.Tcp);

                socket.Connect(remoteEP);
                Receive();
//接收
                sendThread = new Thread(new ThreadStart(Send));//启动发送。
                sendThread.Start();
                
// Release the socket.
                
//socket.Shutdown(SocketShutdown.Both);
                
//socket.Close();

            }
            
catch (Exception e)
            {
                
//Console.WriteLine(e.ToString());
                throw new Exception(e.Message);
            }
        }
以上是接受并且发送。接收处理如下:
ContractedBlock.gifExpandedBlockStart.gifCode
        private void Receive()
        {
            
try
            {
                
// Create the state object.
                StateObject state = new StateObject();
                state.workSocket 
= this.socket;
                
// Begin receiving the data from the remote device.
                this.socket.BeginReceive(state.buffer, 0, state.BufferSize, 0,
                    
new AsyncCallback(ReceiveCallback), state);
            }
            
catch (Exception e)
            {
                
throw new Exception(e.Message);
            }
        }

        
private void ReceiveCallback(IAsyncResult ar)
        {
            
try
            {
                
// Retrieve the state object and the client socket 
                
// from the asynchronous state object.
                StateObject state = (StateObject)ar.AsyncState;
                Socket client 
= state.workSocket;

                
// Read data from the remote device.
                int bytesRead = client.EndReceive(ar);

                
if (bytesRead > 0)
                {
                    
this.isReceive = true;
                    
//处理接收的数据。
                    ReceivePacketManager.ReceivePacket(state.buffer);
                    client.BeginReceive(state.buffer, 
0, state.BufferSize, 0,
                       
new AsyncCallback(ReceiveCallback), state);
                }
                
else
                {
                    ReceivePacketManager.isDataOver 
= true;
                    
this.isReceive = false;
                    client.BeginReceive(state.buffer, 
0, state.BufferSize, 0,
                       
new AsyncCallback(ReceiveCallback), state);
                }
            }
            
catch (Exception e)
            {
                
throw new Exception(e.Message);
            }
        }
发送时单独起的线程,如下:
ContractedBlock.gifExpandedBlockStart.gifCode
        public bool Send(ISendPacket data)
        {
            
            
this.sendState = new StateObject();
            
this.sendState.workSocket = socket;
            
this.sendState.data = data;
            
this.sendState.buffer = SendPacketManager.SendByte(data);
            
if(!this.isReceive)
            {
                sendDone.Set();
                
return true;
            }
            
return false;
        }
        
        
private void Send()
        {
            
//当收到信号就开始发送
            sendDone.WaitOne();
            socket.BeginSend(sendState.buffer, 
0, sendState.buffer.Length, 0,
               
new AsyncCallback(SendCallback), sendState);
        }

        
private void SendCallback(IAsyncResult ar)
        {
            
try
            {
                StateObject state 
= (StateObject)ar;
                Socket client 
= state.workSocket;
              
                
// Complete sending the data to the remote device.
                int bytesSent = client.EndSend(ar);
                
if (bytesSent > 0)
                { 
//success send
                    if (!SendPacketManager.IsData)
                    {
                        sendDone.WaitOne(); 
                    }
                    
else
                    {
                        state.buffer 
= SendPacketManager.SendByte(state.data);
                        client.BeginSend(state.buffer,
0, state.BufferSize, 0new AsyncCallback(SendCallback), state);
                    }
                }
                
else
                { 
//failed;

                }
            }
            
catch (Exception e)
            {
                
throw new Exception(e.Message);
            }
        }
上面的代码仅仅是客户端的模型,错误控制和处理都没有加进去。服务器端还没有思路,哪位大侠给提供以下思路?

转载于:https://www.cnblogs.com/xingyayang/archive/2009/10/12/1581545.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值