Tcp异步通信代码.docx

上传人:牧羊曲112 文档编号:3166627 上传时间:2023-03-11 格式:DOCX 页数:14 大小:39.11KB
返回 下载 相关 举报
Tcp异步通信代码.docx_第1页
第1页 / 共14页
Tcp异步通信代码.docx_第2页
第2页 / 共14页
Tcp异步通信代码.docx_第3页
第3页 / 共14页
Tcp异步通信代码.docx_第4页
第4页 / 共14页
Tcp异步通信代码.docx_第5页
第5页 / 共14页
亲,该文档总共14页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述

《Tcp异步通信代码.docx》由会员分享,可在线阅读,更多相关《Tcp异步通信代码.docx(14页珍藏版)》请在三一办公上搜索。

1、Tcp异步通信代码Tcp异步通信代码: WinFrm TcpServer代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; using Sy

2、stem.IO; using System.Collections; namespace AsyncTcpServerEx204 public partial class FrmServer : Form public FrmServer InitializeComponent; ArrayList friends = new ArrayList;/保存于客户相关的信息列表 TcpListener listener; /负责侦听的套接字 bool IsStart = false; /指示是否已经启动了侦听 /对控件进行调用委托类型和委托方法 /在列表中写字符串 delegate void Ap

3、pendDelegate(string str); AppendDelegate AppendString; /在建立连接时,向下拉列表框中添加客户信息 delegate void AddDelegate(MyFriend frd); AddDelegate Addfriend; /在断开连接时,从下拉列表框中删除客户信息 delegate void RemoveDelegate(MyFriend frd); RemoveDelegate Removefriend; private AsyncCallback ReceiveCallBack; /在列表中写字符串的委托方法 private vo

4、id AppendMethod(string str) lstBoxStatu.Items.Add(str); lstBoxStatu.SelectedIndex = lstBoxStatu.Items.Count - 1; lstBoxStatu.ClearSelected; /向下拉框中添加信息的委托方法 private void AddMethod(MyFriend frd) lock (friends) friends.Add(frd); comboBoxClient.Items.Add(frd.socket.RemoteEndPoint.ToString); /从下拉列表框中删除信息

5、的委托方法 private void RemoveMethod(MyFriend frd) int i = friends.IndexOf(frd); comboBoxClient.Items.RemoveAt(i); lock (friends) friends.Remove(frd); frd.Dispose; private void btnStart_Click(object sender, EventArgs e) /服务器已经在其中侦听,则返回 if (IsStart) return; /服务器启动侦听 IPEndPoint localEp = new IPEndPoint(Dns

6、.GetHostAddresses(Dns.GetHostName)1,100); listener = new TcpListener(localEp); listener.Start(10); IsStart = true; lstBoxStatu.Invoke(AppendString, string.Format(服务器已经启动侦听!端点为:0。, listener.LocalEndpoint.ToString); /接受连接的异步调用 AsyncCallback callBack = new AsyncCallback(AcceptCallBack); listener.BeginA

7、cceptSocket(callBack, listener); this.btnStart.Enabled = false; private void AcceptCallBack(IAsyncResult ar) try /完成异步接受连接请求的异步调用 将连接信息添加到列表和下拉列表框中 Socket handle = listener.EndAcceptSocket(ar); MyFriend frd = new MyFriend(handle); comboBoxClient.Invoke(Addfriend, frd); AsyncCallback callBack; /继续调用异

8、步方法接受连接请求 if (IsStart) callBack = new AsyncCallback(AcceptCallBack); listener.BeginAcceptSocket(callBack, listener); /开始在连接上进行异步的数据接收 frd.ClearBuffer; callBack = new AsyncCallback(ReceiveCallback); frd.socket.BeginReceive(frd.Rcvbuffer, 0, frd.Rcvbuffer.Length, SocketFlags.None, callBack, frd); catc

9、h /ListBox.Invoke(AppendString); IsStart = false; private void ReceiveCallback(IAsyncResult ar) MyFriend frd = (MyFriend)ar.AsyncState; try int i = frd.socket.EndReceive(ar); if (i = 0) comboBoxClient.Invoke(Removefriend, frd); return; else string data = Encoding.UTF8.GetString(frd.Rcvbuffer, 0, i);

10、 data = string.Format(From0:1, frd.socket.RemoteEndPoint.ToString, data); frd.ClearBuffer; AsyncCallback callBack = new AsyncCallback(ReceiveCallback); frd.socket.BeginReceive(frd.Rcvbuffer, 0, frd.Rcvbuffer.Length, SocketFlags.None, callBack, frd); catch comboBoxClient.Invoke(Removefriend, frd); pr

11、ivate void SendData(MyFriend frd, string data) try byte msg = Encoding.UTF8.GetBytes(data); AsyncCallback callBack = new AsyncCallback(SendCallBack); frd.socket.BeginSend(msg, 0, msg.Length, SocketFlags.None, callBack, frd); data = string.Format(To 0:1, frd.socket.RemoteEndPoint.ToString, data); lst

12、BoxStatu.Invoke(AppendString, data); catch comboBoxClient.Invoke(Removefriend, frd); private void SendCallBack(IAsyncResult ar) MyFriend frd = (MyFriend)ar.AsyncState; try frd.socket.EndSend(ar); catch comboBoxClient.Invoke(Removefriend, frd); private void comboBoxClient_SelectedIndexChanged(object

13、sender, EventArgs e) private void FrmServer_Load(object sender, EventArgs e) /实例化委托对象,与委托方法关联 AppendString = new AppendDelegate(AppendMethod); Addfriend = new AddDelegate(AddMethod); Removefriend = new RemoveDelegate(RemoveMethod); private void btnStop_Click(object sender, EventArgs e) if (!IsStart)

14、 return; listener.Stop; IsStart = false; lstBoxStatu.Invoke(AppendString, 已经结束了服务器的侦听。); this.btnStart.Enabled = true; private void btnSendMess_Click(object sender, EventArgs e) if (txBoxMessage.Text.Trim = ) lstBoxStatu.Items.Add(不能发送空字符串!); txBoxMessage.Focus; return; if (comboBoxClient.SelectedIn

15、dex 0) lstBoxStatu.Items.Add(请在列表框中选择发送对象!); return; int i = comboBoxClient.SelectedIndex; SendData (MyFriend)friendsi,txBoxMessage.Text.Trim); private void btnClear_Click(object sender, EventArgs e) this.lstBoxStatu.Items.Clear; WinFrm TcpClient代码: using System; using System.Collections.Generic; us

16、ing System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; namespace AsyncTcpClientEx205 public partial class FrmClient : Form public FrmClient InitializeComponent; Socket client =

17、null; byte Rcvbuffer; string SendStr; delegate void AppendDelegate(string str); AppendDelegate AppendString; string ipAddress = 172.16.33.79; private void AppendMethod(string str) lstBoxMessage.Items.Add(str); private void ConnectCallBack(IAsyncResult ar) try client.EndConnect(ar); lstBoxMessage.Inv

18、oke(AppendString, String.Format(已经成功连接到服务器0!, client.RemoteEndPoint.ToString); lstBoxMessage.Invoke(AppendString, String.Format(本地端口节点为0!, client.LocalEndPoint.ToString); Rcvbuffer = new byteclient.SendBufferSize; AsyncCallback callback = new AsyncCallback(ReceiveCallBack); client.BeginReceive(Rcvbu

19、ffer, 0, Rcvbuffer.Length, SocketFlags.None, callback, client); catch lstBoxMessage.Invoke(AppendString, String.Format(无法与服务器建立连接!); private void ReceiveCallBack(IAsyncResult ar) try int i = client.EndReceive(ar); string data = string.Format(收:0, Encoding.UTF8.GetString(Rcvbuffer, 0, i); lstBoxMessa

20、ge.Invoke(AppendString, data); Rcvbuffer = new byteclient.SendBufferSize; AsyncCallback callback = new AsyncCallback(ReceiveCallBack); client.BeginReceive(Rcvbuffer, 0, Rcvbuffer.Length, SocketFlags.None, callback, client); catch(Exception ex) if (client != null) client.Shutdown(SocketShutdown.Both)

21、; client.Close; client = null; lstBoxMessage.Invoke(AppendString, ex.Message); private void SendData try byte msg = Encoding.UTF8.GetBytes(SendStr); AsyncCallback callback = new AsyncCallback(SendCallBack); client.BeginSend(msg, 0, msg.Length, SocketFlags.None, callback, client); catch client.Shutdo

22、wn(SocketShutdown.Both); client.Close; client = null; lstBoxMessage.Invoke(AppendString, 服务器断开了Tcp连接!); private void SendCallBack(IAsyncResult ar) try client.EndSend(ar); lstBoxMessage.Invoke(AppendString,string.Format(发:0,SendStr); catch client.Shutdown(SocketShutdown.Both); client.Close; client =

23、null; lstBoxMessage.Invoke(AppendString, 服务器断开了Tcp连接!); private void btnClose_Click(object sender, EventArgs e) if (client = null) return; if (!client.Connected) return; client.Shutdown(SocketShutdown.Both); client.Close(50); client = null; lstBoxMessage.Items.Add(断开了到服务器的Tcp连接!); private void btnCo

24、nnect_Click(object sender, EventArgs e) if (client = null) /client = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); if (!client.Connected) try IPAddress i = IPAddress.Parse(172.16.33

25、.46); /IPEndPoint remoteEp = new IPEndPoint(Dns.GetHostAddresses(Dns.GetHostName)0, 100); IPEndPoint remoteEp = new IPEndPoint(i, 100); AsyncCallback callback = new AsyncCallback(ConnectCallBack); /client = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); client = new S

26、ocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.BeginConnect(remoteEp, callback, client); catch (SocketException se) lstBoxMessage.Invoke(AppendString, String.Format(se.ToString); private void btnClear_Click(object sender, EventArgs e) this.lstBoxMessage.Items.Clear; p

27、rivate void btnSend_Click(object sender, EventArgs e) if (txtBoxSendMess.Text.Trim = ) lstBoxMessage.Items.Add(不能发送空字符串!); txtBoxSendMess.Focus; return; if (client = null) lstBoxMessage.Items.Add(尚未建立到服务器的连接!); btnConnect.Focus; return; if (!client.Connected) lstBoxMessage.Items.Add(尚未建立到服务器的连接!); btnConnect.Focus; return; SendStr = txtBoxSendMess.Text.Trim; SendData; private void FrmClient_Load(object sender, EventArgs e) AppendString = new AppendDelegate(AppendMethod);

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 生活休闲 > 在线阅读


备案号:宁ICP备20000045号-2

经营许可证:宁B2-20210002

宁公网安备 64010402000987号