php winform socket,C#上位机之—WinForm实现Socket异步通讯示例

工作中常用到的一些知识点,总是用完就忘,第一次尝试用博客记录下来,以备后用;

Socket通讯,Socket(套接字)是基于TCP/IP通讯方式的封装好的类,调用时需要添加下面的服务引用:

.......10 usingSystem.Net;11 using System.Net.Sockets;

窗体页面搭建,上面为服务器区,下面为客户端区:

c443296d5dea1d51f2a0d37bfb250dd0.png

建立两个类,一个表示服务器,一个表示客户端,

首先建立服务器类:

1.声明变量:IP地址,端口号,EndPoint,Socket类,数据Buffer等

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 string ip;//IP地址

2 string port;//端口号

3 IPEndPoint endPoint;//网络端点

4 Socket socServer;//侦听连接套接字

5 Socket socClient;//通讯套接字

6 byte[] dataReceived = new byte[50000];7

8 public delegate void delegateDisplayMsg(string type,stringmsg);9 publicdelegateDisplayMsg OnDisplay;10

11 publicSocketServer()12 {13 socServer = newSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);14 }

View Code

2.侦听连接函数:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

public void StartListen(string ip,stringport)

{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.接受数据函数:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

public voidOnClientConnect(IAsyncResult asyn)

{

socClient=socServer.EndAccept(asyn);

WaitForData();

ShowMsg("Client Connected" +socClient.RemoteEndPoint.ToString());

}public voidWaitForData()

{if (socClient != null)

socClient.BeginReceive(dataReceived,0, dataReceived.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);

}public voidOnDataReceived(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.发送数据函数:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

public void SendMsg(stringmsg)

{byte[] data =Encoding.Default.GetBytes(msg);

socClient.Send(data);

ShowMsg("=>" +msg);

}

View Code

然后建立客户端类:

1.声明变量

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

string ip;//IP地址

string port;//端口号

IPEndPoint endPoint;//网络端点

Socket socClient;//通讯套接字

byte[] dataReceived = new byte[50000];//数据Buffer

public delegate void delegateDisplayMsg(string type,stringmsg);publicdelegateDisplayMsg OnDisplay;publicSocketClient()

{

socClient= newSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

}

View Code

2.连接服务器函数:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

public void Connect(string ip, stringport)

{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.接受数据函数:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

public voidOnToConnected(IAsyncResult asyn)

{

socClient.EndConnect(asyn);

WaitForData();

ShowMsg("Connect Success");

}public voidWaitForData()

{if (socClient != null)

socClient.BeginReceive(dataReceived,0, dataReceived.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);

}public voidOnDataReceived(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.发送数据函数:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

public void SendMsg(stringmsg)

{byte[] data =Encoding.Default.GetBytes(msg);

socClient.Send(data);

ShowMsg("=>" +msg);

}

View Code

服务器类与客户端类,已经建立完成,下面对两个类进行实例化,并Link窗体控件的事件函数,如下:

1.实例化:

public voidInit()

{

Server= newSocketServer();

Client= newSocketClient();

Server.OnDisplay+=ShowMsg;

Client.OnDisplay+=ShowMsg;

}

2.按钮点击事件:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

private void btn_StartListen_Click(objectsender, EventArgs e)

{

Server.StartListen(txt_serverIP.Text.ToString(), txt_serverPort.Text.ToString());

btn_StartListen.BackColor=Color.LimeGreen;

}private void btn_Connect_Click(objectsender, EventArgs e)

{

Client.Connect(txt_clientIP.Text.ToString(), txt_clientPort.Text.ToString());

}private void btn_serverSend_Click(objectsender, EventArgs e)

{

Button b=(Button)sender;bool isServer = b.Name.Contains("server");if(isServer)

Server.SendMsg(txt_serverMsg.Text.ToString());elseClient.SendMsg(txt_clientMsg.Text.ToString());

}

View Code

现在启动程序,测试发送接收功能是否正常

a60505c9dd97131ef95b64fd86514d19.png

至此,一个简单的Socket通讯模型已经完成,实际应用中还需考虑通讯异常,通讯协议,多个客户端通讯等事项,第一次写博,欢迎大家多多指正;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值