C#上位机之—WinForm实现Socket异步通讯⽰例⼯作中常⽤到的⼀些知识点,总是⽤完就忘,第⼀次尝试⽤博客记录下来,以备后⽤;
Socket通讯,Socket(套接字)是基于TCP/IP通讯⽅式的封装好的类,调⽤时需要添加下⾯的服务引⽤:.......
10using System.Net;
11using System.Net.Sockets;
窗体页⾯搭建,上⾯为服务器区,下⾯为客户端区:
建⽴两个类,⼀个表⽰服务器,⼀个表⽰客户端,
⾸先建⽴服务器类:
1.声明变量:IP地址,端⼝号,EndPoint,Socket类,数据Buffer等
1string ip;//IP地址
2string port;//端⼝号
3 IPEndPoint endPoint;//⽹络端点
4 Socket socServer;//侦听连接套接字
5 Socket socClient;//通讯套接字
6byte[] dataReceived = new byte[50000];
7
8public delegate void delegateDisplayMsg(string type,string msg);
9public delegateDisplayMsg OnDisplay;
10
11public SocketServer()
12 {
13 socServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
14 }
View Code
2.侦听连接函数:
public void StartListen(string ip,string port)
{
this.ip = ip;
this.port = port;
endPoint = new IPEndPoint(IPAddress.Parse(this.ip), int.Parse(port));
socServer.Bind(endPoint);
socServer.Listen(0);
socServer.BeginAccept(new AsyncCallback(OnClientConnect), null);
ShowMsg("Wait Connect");
}
View Code
3.接受数据函数:
public void OnClientConnect(IAsyncResult asyn)
{
socClient = socServer.EndAccept(asyn);
WaitForData();
ShowMsg("Client Connected " + socClient.RemoteEndPoint.ToString());
}
public void WaitForData()
{
if (socClient != null)
socket通信报文格式socClient.BeginReceive(dataReceived, 0, dataReceived.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null); }
public void OnDataReceived(IAsyncResult asyn)
{
int dataLength = socClient.EndReceive(asyn);
byte[] chars = new byte[dataLength];
Buffer.BlockCopy(dataReceived, 0, chars, 0, dataLength);
string msg = Encoding.ASCII.GetString(chars);
ShowMsg("<=" + msg);
WaitForData();
}
View Code
4.发送数据函数:
public void SendMsg(string msg)
{
byte[] data = Encoding.Default.GetBytes(msg);
socClient.Send(data);
ShowMsg("=>" + msg);
}
View Code
然后建⽴客户端类:
1.声明变量
string ip;//IP地址
string port;//端⼝号
IPEndPoint endPoint;//⽹络端点
Socket socClient;//通讯套接字
byte[] dataReceived = new byte[50000];//数据Buffer
public delegate void delegateDisplayMsg(string type,string msg);
public delegateDisplayMsg OnDisplay;
public SocketClient()
{
socClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
View Code
2.连接服务器函数:
public void Connect(string ip, string port)
{
this.ip = ip;
this.port = port;
endPoint = new IPEndPoint(IPAddress.Parse(this.ip), int.Parse(port));
socClient.BeginConnect(endPoint, new AsyncCallback(OnToConnected), null);
}
View Code
3.接受数据函数:
public void OnToConnected(IAsyncResult asyn)
{
socClient.EndConnect(asyn);
WaitForData();
ShowMsg("Connect Success");
}
public void WaitForData()
{
if (socClient != null)
socClient.BeginReceive(dataReceived, 0, dataReceived.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null); }
public void OnDataReceived(IAsyncResult asyn)
{
int dataLenth = socClient.EndReceive(asyn);
byte[] chars = new byte[dataLenth];
Buffer.BlockCopy(dataReceived, 0, chars, 0, dataLenth);
string msg = Encoding.ASCII.GetString(chars);
ShowMsg("<=" + msg);
WaitForData();
}
View Code
4.发送数据函数:
public void SendMsg(string msg)
{
byte[] data = Encoding.Default.GetBytes(msg);
socClient.Send(data);
ShowMsg("=>" + msg);
}
View Code
服务器类与客户端类,已经建⽴完成,下⾯对两个类进⾏实例化,并Link窗体控件的事件函数,如下:
1.实例化:
public void Init()
{
Server = new SocketServer();
Client = new SocketClient();
Server.OnDisplay += ShowMsg;
Client.OnDisplay += ShowMsg;
}
2.按钮点击事件:
private void btn_StartListen_Click(object sender, EventArgs e)
{
Server.StartListen(txt_serverIP.Text.ToString(), txt_serverPort.Text.ToString());
btn_StartListen.BackColor = Color.LimeGreen;
}
private void btn_Connect_Click(object sender, EventArgs e)
{
Client.Connect(txt_clientIP.Text.ToString(), txt_clientPort.Text.ToString());
}
private void btn_serverSend_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
bool isServer = b.Name.Contains("server");
if (isServer)
Server.SendMsg(txt_serverMsg.Text.ToString());
else
Client.SendMsg(txt_clientMsg.Text.ToString());
}
View Code
现在启动程序,测试发送接收功能是否正常
⾄此,⼀个简单的Socket通讯模型已经完成,实际应⽤中还需考虑通讯异常,通讯协议,多个客户端通讯等事项,第⼀次写博,欢迎⼤家多多指正;
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论