版权声明:博客内容仅代表个人观点,如发现阐述有误,麻烦指正,谢谢! https://blog.csdn.net/heyangyi_19940703/article/details/75316619
C#Socket 网络通信异步处理 SocketAsyncEventArgs 异步套接字操作
1.服务端简单实现:
Code:
public partial class Form_Server : Form
{
private Socket socket;
public Form_Server()
{
InitializeComponent();
}
private void Form_Server_Load(object sender, EventArgs e)
{
try
{
//获取本地ip地址
IPAddress ipaddress = Dns.GetHostByName(Dns.GetHostName()).AddressList[0];
txt_ip.Text = ipaddress.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//开启Socket监听
private void btn_listent_open_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(txt_ip.Text))
{
MessageBox.Show("请输入IP地址");
}
//打开监听
IPAddress ip = IPAddress.Parse(txt_ip.Text);
IPEndPoint localEP = new IPEndPoint(ip, Int32.Parse(txt_port.Text));
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(localEP);
socket.Listen(1000);
//AcceptAsync异步方式
SocketAsyncEventArgs socketAsyncEventArgs = new SocketAsyncEventArgs();
socketAsyncEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(socketAsyncEventArgs_Completed_AcceptAsync);
socketAsyncEventArgs.RemoteEndPoint = localEP;
socketAsyncEventArgs.UserToken = socket;
socket.AcceptAsync(socketAsyncEventArgs);
//消息提示
this.lb_msg.Items.Add("[服务端]:");
this.lb_msg.Items.Add(" 监听成功");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//开始一个异步操作来接受一个传入的连接尝试
void socketAsyncEventArgs_Completed_AcceptAsync(object ServerSocket, SocketAsyncEventArgs e)
{
//已关闭,重叠的操作被中止
if (e.SocketError == SocketError.OperationAborted)
{
//已关闭,重叠的操作被中止
this.lb_msg.Invoke(new Action(() =>
{
this.lb_msg.Items.Add("[服户端]:");
this.lb_msg.Items.Add(" socketAsyncEventArgs_Completed_AcceptAsync:已关闭,重叠的操作被中止>SocketError:OperationAborted");
}));
return;
}
//此连接由远程对等计算机重置
if (e.SocketError == SocketError.ConnectionReset && e.BytesTransferred == 0)
{
//此连接由远程对等计算机重置
this.lb_msg.Invoke(new Action(() =>
{
this.lb_msg.Items.Add("[服户端]:");
this.lb_msg.Items.Add(" socketAsyncEventArgs_Completed_AcceptAsync:此连接由远程对等计算机重置>SocketError:ConnectionReset");
}));
return;
}
if (e.LastOperation == SocketAsyncOperation.Accept)
{
try
{
Socket acceptSocket = e.AcceptSocket;
//开始一个异步请求以便从连接的 System.Net.Sockets.Socket 对象中接收数据
SocketAsyncEventArgs socketAsyncEventArgsReceiveAsync = new SocketAsyncEventArgs();
socketAsyncEventArgsReceiveAsync.UserToken = acceptSocket;
byte[] receiveBuff = new byte[1024 * 4];
socketAsyncEventArgsReceiveAsync.SetBuffer(receiveBuff, 0, receiveBuff.Length);
socketAsyncEventArgsReceiveAsync.Completed += new EventHandler<SocketAsyncEventArgs>(socketAsyncEventArgs_Completed_ReceiveAsync);
acceptSocket.ReceiveAsync(socketAsyncEventArgsReceiveAsync);
//消息提示
this.lb_msg.Invoke(new Action(() =>
{
this.lb_msg.Items.Add("[客户端]:");
this.lb_msg.Items.Add(" 连接成功");
}));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
//开始一个异步操作来接受一个传入的连接尝试,递归
e.AcceptSocket = null;
socket.AcceptAsync(e);
}
}
//开始一个异步请求以便从连接的 System.Net.Sockets.Socket 对象中接收数据
void socketAsyncEventArgs_Completed_ReceiveAsync(object acceptSocket, SocketAsyncEventArgs e)
{
//已关闭,重叠的操作被中止
if (e.SocketError == SocketError.OperationAborted)
{
//已关闭,重叠的操作被中止
this.lb_msg.Invoke(new Action(() =>
{
this.lb_msg.Items.Add("[服户端]:");
this.lb_msg.Items.Add(" socketAsyncEventArgs_Completed_ReceiveAsync:已关闭,重叠的操作被中止>SocketError:OperationAborted");
}));
return;
}
//此连接由远程对等计算机重置
if (e.SocketError == SocketError.ConnectionReset && e.BytesTransferred == 0)
{
//此连接由远程对等计算机重置
this.lb_msg.Invoke(new Action(() => {
this.lb_msg.Items.Add("[服户端]:");
this.lb_msg.Items.Add(" socketAsyncEventArgs_Completed_ReceiveAsync:此连接由远程对等计算机重置>SocketError:ConnectionReset");
}));
return;
}
if (e.SocketError == SocketError.Success && e.Buffer.Length > 0)
{
try
{
Socket socket = acceptSocket as Socket;
string ipAddress = socket.RemoteEndPoint.ToString();
int lengthuffer = e.BytesTransferred;
byte[] receiveBuffer = e.Buffer;
byte[] buffer = new byte[lengthuffer];
Buffer.BlockCopy(receiveBuffer, 0, buffer, 0, lengthuffer);
string message = Encoding.UTF8.GetString(buffer);
this.lb_msg.Invoke(new Action(() =>
{
this.lb_msg.Items.Add("[客户端]:");
this.lb_msg.Items.Add(" " + message);
}));
socket.Send(Encoding.UTF8.GetBytes(string.Format("收到消息{0}:{1}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), message)));
socket.ReceiveAsync(e);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
//关闭Socket监听
private void btn_listent_Close_Click(object sender, EventArgs e)
{
try
{
if (socket != null)
{
socket.Close();
}
this.lb_msg.Items.Add("[服务端]:");
this.lb_msg.Items.Add(" 关闭监听成功");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
2.客户端简单实现:
Code:
public partial class ClientMainForm : Form
{
private Socket _socket;
public ClientMainForm()
{
InitializeComponent();
}
//登录
private void btn_login_Click(object sender, EventArgs e)
{
try
{
IPAddress ip = IPAddress.Parse(this.txt_ip.Text);
IPEndPoint ipendPoint = new IPEndPoint(ip, Int32.Parse(this.txt_port.Text));
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Connect(ipendPoint);
this.lb_msg.Items.Add("[客户端]:");
this.lb_msg.Items.Add(" 连接服务端成功");
//开启新的接受消息异步操作事件
SocketAsyncEventArgs socketAsyncEventArgs = new SocketAsyncEventArgs();
//设置消息的缓冲区大小
byte[] receiveBuff = new byte[1024 * 4];
socketAsyncEventArgs.SetBuffer(receiveBuff, 0, receiveBuff.Length);
socketAsyncEventArgs.UserToken = _socket;
//绑定回调事件
socketAsyncEventArgs.Completed += socketAsyncEventArgs_Completed_ReceiveAsync;
_socket.ReceiveAsync(socketAsyncEventArgs);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//开始一个异步请求以便从连接的 System.Net.Sockets.Socket 对象中接收数据。
void socketAsyncEventArgs_Completed_ReceiveAsync(object sender, SocketAsyncEventArgs e)
{
//已关闭,重叠的操作被中止
if (e.SocketError == SocketError.OperationAborted)
{
this.lb_msg.Invoke(new Action(() =>
{
this.lb_msg.Items.Add("[客户端]:");
this.lb_msg.Items.Add(" socketAsyncEventArgs_Completed_ReceiveAsync:已关闭,重叠的操作被中止:OperationAborted");
}));
return;
}
//此连接由远程对等计算机重置
if (e.SocketError == SocketError.ConnectionReset && e.BytesTransferred == 0)
{
//此连接由远程对等计算机重置
this.lb_msg.Invoke(new Action(() =>
{
this.lb_msg.Items.Add("[客户端]:");
this.lb_msg.Items.Add(" socketAsyncEventArgs_Completed_ReceiveAsync:此连接由远程对等计算机重置:ConnectionReset");
}));
return;
}
Socket socket = sender as Socket;
if(e.SocketError==SocketError.Success&&e.Buffer.Length>0)
{
string ipAddress = socket.RemoteEndPoint.ToString();
int lengthuffer = e.BytesTransferred;
byte[] receiveBuffer = e.Buffer;
byte[] buffer = new byte[lengthuffer];
Buffer.BlockCopy(receiveBuffer, 0, buffer, 0, lengthuffer);
string message = Encoding.UTF8.GetString(buffer);
this.lb_msg.Invoke(new Action(() =>
{
this.lb_msg.Items.Add("[服务户端]:");
this.lb_msg.Items.Add(" " + message);
}));
socket.ReceiveAsync(e);
}
}
//发送消息
private void btn_sendmsg_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txt_msg.Text))
{
MessageBox.Show("请输入消息");
}
else
{
_socket.Send(System.Text.Encoding.UTF8.GetBytes(txt_msg.Text));
}
}
}