zoukankan      html  css  js  c++  java
  • TcpClient 简单通讯示例

    public class TcpClient
        {
            //声明IP,端口,和一个用来连接的Socket
            private string _ip;
            private int _port;
            private TcpClient _tcpClient;
            
            //创建一个委托,用来满足其他类调用
            public delegate void DelegateMessage(byte[] bytes) ;
            public event DelegateMessage OnmessageEvent;
     
            /// <summary>
            /// 构造函数
            /// </summary>
            /// <param name="remoteIp">IP地址</param>
            /// <param name="remotePort">端口号</param>
            public  TcpClient(string remoteIp,int remotePort)
            {
                this._ip = remoteIp;
                this._port = remotePort;
            }
     
            //TCP连接
            public bool Connect()
            {
                _tcpClient = new TcpClient();
                try
                {
                    _tcpClient.Connect(IPAddress.Parse(_ip), _port);
                    Task.Run(new Action(ReceiveMessage));//开启线程,不停接收消息
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
                return true;//返回连接状态
            }
     
            /// <summary>
            /// 发送消息
            /// </summary>
            /// <param name="bytes">需要发送的字节</param>
            public void SendMessage(byte[] bytes)
            {
                NetworkStream networkStream = _tcpClient.GetStream();
                networkStream.Write(bytes, 0, bytes.Length);
            }
     
     
            //接收消息
            public void ReceiveMessage()
            {
                NetworkStream networkStream = _tcpClient.GetStream();
                while (true)
                {
                    byte[] buffer = new byte[8];
                    int size = networkStream.Read(buffer, 0, buffer.Length);
                    OnmessageEvent?.Invoke(buffer);
                }            
            }
     
        
    

      另摘另外一个:https://blog.csdn.net/qq_28602957/article/details/53443600

    1.  
    2.  
    3.  
       
  • 相关阅读:
    学习进度06
    求最大子数组03
    js实现标签绑定回车事件
    ImageDown
    ImageUpload
    XMLProcess
    VideoConvert
    SmtpServerHelper
    SharpZip(压缩帮助类)
    SessionHelper
  • 原文地址:https://www.cnblogs.com/baylor2019/p/13608484.html
Copyright © 2011-2022 走看看