客户端直接照搬:https://blog.csdn.net/fuemocheng/article/details/78241405
服务器端:https://github.com/tangxuehua/SocketAsyncEventArgsSample
服务器接收数据模块没有问题,发送数据需要做如下更改:
声明变量:
private SocketAsyncEventArgs m_sendSAEA = new SocketAsyncEventArgs();
MessageData sendData = new MessageData();
在private void ProcessAccept(SocketAsyncEventArgs e)
函数中,设置发送对象:
编写发送模块:
public void Send(byte[] sendBuffer)
{
sendData.Message = sendBuffer;
sendingQueue.Add(sendData);
}
private void ProcessSend(SocketAsyncEventArgs e)
{
_socketAsyncSendEventArgsPool.Push(e);
waitSendEvent.Set();
}
private void SendQueueMessage()
{
while (true)
{
var messageData = sendingQueue.Take();
if (messageData != null)
{
SendMessage(messageData, messageData.Message);
}
}
}
private void SendMessage(MessageData messageData, byte[] message)
{
var sendEventArgs = _socketAsyncSendEventArgsPool.Pop();
if (sendEventArgs != null)
{
sendEventArgs.SetBuffer(message, 0, message.Length);
sendEventArgs.UserToken = messageData.Token;
messageData.Token.Socket.SendAsync(sendEventArgs);
}
else
{
waitSendEvent.WaitOne();
SendMessage(messageData, message);
}
}
调用发送函数:
string msg = "要发送的内容";
byte[] sendBuffer = Encoding.Default.GetBytes(msg);
Send(sendBuffer);