• C#学习笔记——TCP通讯



    服务端:TcpListener

    客户端:TcpClient、NetworkStream

    (要熟悉的类,请参照MSDN。)


    TCP客户端:

    界面:

    image

    代码:

     
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    //引入命名空间
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
     
    namespace CSharp_003_同步TCP客户端
    {
        public partial class frmMain : Form
        {
            //定义回调//定义委托
            private delegate void ShowReceiveMsgCallBack(string text);
            //声明回调//声明委托
            private ShowReceiveMsgCallBack showReceiveMsgCallBack;
            //定义回调
            private delegate void SetProgressBarValueCallBack();
            //声明回调
            private SetProgressBarValueCallBack setProgressBarValueCallBack;
     
            private TcpClient myTcpClient;  //声明TCP客户端
            private NetworkStream netStream;    //声明网络数据流
            private Thread receiveDataThread;   //声明接收数据进程
     
     
            public frmMain()
            {
                InitializeComponent();
            }
     
            private void frmMain_Load(object sender, EventArgs e)
            {
                //初始化回调//实例化委托
                showReceiveMsgCallBack = new ShowReceiveMsgCallBack(AddMsgToList);
                //初始化回调
                setProgressBarValueCallBack = new SetProgressBarValueCallBack(SetProgressBarValue);
            }
     
            private void btnConnect_Click(object sender, EventArgs e)
             {
                 //创建并实例化IP终结点
                 IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse(txtServerIp.Text), Convert.ToInt32(txtServerPort.Text));
                 //实例化TCP客户端
                 myTcpClient = new TcpClient();
                 try
                 {
                     //发起TCP连接
                     myTcpClient.Connect(iPEndPoint);
                     //获取绑定的网络数据流
                     netStream = myTcpClient.GetStream();
                     //实例化接收数据进程
                     receiveDataThread = new Thread(ReceiveMsg);
                     receiveDataThread.Start();
                 }
                 catch (System.Exception ex)
                 {
                     MessageBox.Show(ex.Message);
                 }
           
             }
     
            //接收消息线程
            private void ReceiveMsg()
            {
                MessageBox.Show("客户端已连接服务器!");
     
               while (true)
               {
                    try
                    {
                        //获取数据
                        byte[] getData = new byte[1024];
                        netStream.Read(getData,0,getData.Length);
                        //转换为字符串形式
                        string strMsg = Encoding.Default.GetString(getData);
                        //将接收的消息添加到列表中//调用回调
                        lstReceiveMsg.Invoke(showReceiveMsgCallBack,strMsg);
                        //改变进度条
                        pgMsg.Invoke(setProgressBarValueCallBack);
                    }
                    catch(ThreadAbortException)
                    {
     
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        //释放相关资源
                        if(netStream != null)
                        {
                            netStream.Dispose();
                        }
                        break;
                    }
               }
            }
            
            //回调函数的实现函数//被委托的函数
            private void AddMsgToList(string text)
            {
                lstReceiveMsg.Items.Add(text);
            }
     
            //回调函数的实现函数
            private void SetProgressBarValue()
            {
                if (pgMsg.Maximum == pgMsg.Value)
                {
                    pgMsg.Value = 1;
                }
                else
                {
                    pgMsg.Value++;
                }
            }
     
            private void btnSendMsg_Click(object sender, EventArgs e)
            {
                byte[] sendData;
                sendData=Encoding.Default.GetBytes(txtMsg.Text);
                netStream.Write(sendData,0,sendData.Length);
            }
     
            private void btnDisConnect_Click(object sender, EventArgs e)
            {
                //销毁TCP客户端和网络数据流的实例
                myTcpClient.Close();
                netStream.Dispose();
                receiveDataThread.Abort();
            }
     
            
        }
    }

    TCP服务端:

    界面:

    image

    代码:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
     
    namespace CSharp_003服务端
    {
        public partial class frmMain : Form
        {
            //定义回调//定义委托
            private delegate void ShowReceiveMsgCallBack(string text);
            //声明回调//声明委托
            private ShowReceiveMsgCallBack showReceiveMsgCallBack;
     
            private TcpListener server;   //声明Tcp监听对象
            private Thread tcpListenerThread;   //声明Tcp监听线程
            private Int32 port;     //端口号
            private IPAddress localAddr;    //本地IP地址
            private Thread receiveDataThread;   //声明接收数据的线程
     
            public frmMain()
            {
                InitializeComponent();
            }
     
            private void btnListen_Click(object sender, EventArgs e)
            {
                string strPort = txtServerPort.Text;
                if (strPort == "")
                {
                    MessageBox.Show("请输入监听端口");
                    return;
                }
               try
               {
                   // 设置监听的端口
                   port = Int32.Parse(strPort);
                   localAddr = IPAddress.Parse("127.0.0.1");
                   if (port > 0)
                    {
                        //启动服务端监听线程
                       tcpListenerThread = new Thread(StartListenerTcp);
                       tcpListenerThread.Start();
                    }
                    else
                        MessageBox.Show("监听端口号必须大于0,建议使用大于1024的端口");
               }
               catch (System.Exception ex)
               {
                   
               }
        }
     
            //Tcp监听线程的实现函数
            private void StartListenerTcp()
            {
                server = new TcpListener(localAddr, port);
                server.Start(); // 开始监听客户端的申请
                MessageBox.Show("服务已启动。。。");
                
                
                try
                {
                    //启动接收数据的线程
                    receiveDataThread = new Thread(ReceiveMsg);
                    receiveDataThread.Start();
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                    receiveDataThread.Abort();
                }
                
            }
     
            //接收消息线程的实现函数
            private void ReceiveMsg()
            {
                TcpClient client = server.AcceptTcpClient();
                NetworkStream netStream = client.GetStream();
                while (true)
                {
                    try
                    {
                        netStream = client.GetStream();
                        //获取数据
                        byte[] getData = new byte[1024];
                        netStream.Read(getData, 0, getData.Length);
                        //转换为字符串形式
                        string strMsg = Encoding.Default.GetString(getData);
                        //将接收的消息添加到列表中//调用回调
                        lstReceiveMsg.Invoke(showReceiveMsgCallBack, strMsg);
                        //将数据返回
                        netStream.Write(getData, 0, getData.Length);
                    }
                    catch (ThreadAbortException)
                    {
     
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        //释放相关资源
                        if (netStream != null)
                        {
                            netStream.Dispose();
                        }
                        break;
                    }
                }
            }
     
           
     
            //回调函数的实现函数//被委托的函数
            private void AddMsgToList(string text)
            {
                lstReceiveMsg.Items.Add(text);
            }
     
            private void frmMain_Load(object sender, EventArgs e)
            {
                //初始化回调//实例化委托
                showReceiveMsgCallBack = new ShowReceiveMsgCallBack(AddMsgToList);
            }
        }
    }
  • 相关阅读:
    [轉]windows下mysql 启动 mysqlbinlog二进制日志文件
    [轉]MySQL创建、删除、重建和查看索引命令
    [轉]PHP权限控制系统PHPGACL
    [轉]mysql5存储过程语法
    Web Application Stress Tool(WAS) & SQLIOSim
    information_schema資料庫表信息
    [轉]MySQL系统变量应用探究
    [轉]httping 1.5.2 发布,HTTP连接响应测试
    [轉]批处理命令手册
    Google Native Client介紹
  • 原文地址:https://www.cnblogs.com/hanzhaoxin/p/2916886.html
Copyright © 2020-2023  润新知