C# TCP同步客户端

    xiaoxiao2021-03-25  115

    最近在学网络编程

    就心血来潮做了一个TCP同步客户端

    主要用到了TCPClient知识和回调知识

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; namespace TCP同步客户端 { public partial class Form1 : Form { #region 回调 private delegate void ShowMsgCallBack(string Msg); ShowMsgCallBack showMsgCallBack; #endregion #region 字段 TcpClient myTcpClient; NetworkStream ns; Thread receiveThread; #endregion #region 窗体事件 public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { showMsgCallBack = new ShowMsgCallBack(ShowMsg); } #endregion #region 控件事件 private void btnRequest_Click(object sender, EventArgs e)//请求连接 { IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(txtIP.Text), Convert.ToInt32(txtPort.Text)); myTcpClient = new TcpClient(); try { //发起TCP连接 myTcpClient.Connect(ipEndPoint); //获得绑定的网络数据流 ns = myTcpClient.GetStream(); //实例化并启动接受消息线程 receiveThread = new Thread(ReceiveMsg); receiveThread.Start(); //修改控件状态 btnRequest.Enabled = false; btnBreak.Enabled = true; btnSend.Enabled = true; } catch(Exception ex) { MessageBox.Show(ex.Message); } } private void btnBreak_Click(object sender, EventArgs e)//断开连接 { //断开TCP连接 myTcpClient.Close(); //销毁绑定的网络数据流 ns.Dispose(); //销毁接受消息的线程 receiveThread.Abort(); //修改控件状态 btnRequest.Enabled = true; btnBreak.Enabled = false; btnSend.Enabled = false; } private void btnSend_Click(object sender, EventArgs e)//发送消息 { //将要发送的文本转换为字符数组形式 byte[] sendData = Encoding.Default.GetBytes(txtsend.Text); //将数据写入到网络数据流中 ns.Write(sendData, 0, sendData.Length); } #endregion #region 线程 private void ReceiveMsg() { while (true) { try { //创建接受数据的字节流 byte[] getData = new byte[1024]; //从网络流中读取数据 ns.Read(getData, 0, getData.Length); //将字节数组转换成文本形式 string getMsg = Encoding.Default.GetString(getData); //将消息添加到接受消息列表中 lstMessage.Invoke(showMsgCallBack, getMsg); } catch (ThreadAbortException) { //捕捉到线程被终止异常则表示是人为的断开TCP连接 //不弹出错误提示 } catch (Exception e) { //接受消息发生异常 MessageBox.Show(e.Message); //并释放相关资源 if (ns != null) ns.Dispose(); break; } } } #endregion #region 回调 private void ShowMsg(string msg) { lstMessage.Items.Add(msg); } #endregion } } 在自己电脑上做测试时,可以把IP设置为127.0.0.1 端口随便设置一个没被占用的就行

    转载请注明原文地址: https://ju.6miu.com/read-15627.html

    最新回复(0)