我是靠谱客的博主 体贴菠萝,最近开发中收集的这篇文章主要介绍C# WinForm实现TCP收发信息,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

需要定义

         /// <summary>
        /// 负责通信的socket
        /// </summary>
        Socket socketSend;
        /// <summary>
        /// 负责监听Socket
        /// </summary>
        Socket socket;
        /// <summary>
        /// 存放连接的socket
        /// </summary>
        Dictionary<string, Socket> dictionary = new Dictionary<string, Socket>();

监听IP、端口

 //取消跨线程检查
            Control.CheckForIllegalCrossThreadCalls = false;
            //将窗口最大化
            this.WindowState = FormWindowState.Maximized;
            //创建监听的socket,
            //SocketType.Stream 流式对应tcp协议
            //Dgram,数据报对应UDP协议
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //创建IP地址和端口号
            IPAddress ip = IPAddress.Parse("192.166.2.48");//IPAddress.Parse(textServerIP.Text);
            int port = Convert.ToInt32(5555);
            IPEndPoint iPEndPoint = new IPEndPoint(ip, port);
            //让负责监听的Socket绑定ip和端口号
            socket.Bind(iPEndPoint);
            using (StreamWriter sw = new StreamWriter(filePath, true)) { sw.WriteLine("监听成功!" + ip + ";" + port + ":t" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); }
                   
            //设置监听队列
            socket.Listen(10);//一段时间内可以连接到的服务器的最大数量
            Thread thread = new Thread(Listen);
            thread.IsBackground = true;
            thread.Start(socket);
  /// <summary>
        /// 使用线程来接收数据
        /// </summary>
        /// <param name="o"></param>
        private void Listen(object o)
        {
            Socket socket = o as Socket;
            while (true)
            {
                //负责监听的socket是用来接收客户端连接
                //创建负责通信的socket
                socketSend = socket.Accept();
                dictionary.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
               // clientCombo.Items.Add(socketSend.RemoteEndPoint.ToString());      
                //开启新线程,接收客户端发来的信息
                Thread th = new Thread(receive);
                th.IsBackground = true;
                th.Start(socketSend);
            }
        }
  
        //服务器接收客户端传来的消息
        private void receive(object o)
        {
            Socket socketSend = o as Socket;
            while (true)
            {
                try
                {
                    //客户端连接成功后,服务器接收客户端发来的消息
                    byte[] buffer = new byte[1024 * 1024 * 2];//2M大小
                    //接收到的有效字节数
                    int length = socketSend.Receive(buffer);
                    if (length == 0)
                    {
                        using (StreamWriter sw = new StreamWriter(filePath, true)) { sw.WriteLine("TCP连接下线了:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); }
                        
                        dictionary[socketSend.RemoteEndPoint.ToString()].Shutdown(SocketShutdown.Both);
                        dictionary[socketSend.RemoteEndPoint.ToString()].Disconnect(false);
                        dictionary[socketSend.RemoteEndPoint.ToString()].Close();
                        break;
                    }
                    string str = Encoding.ASCII.GetString(buffer, 0, length);
                    //接收过来的消息
                    if (str.Length > 0)
                    {
                        TCPStr = str;
                    }
                  
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

发送消息

  		 Socket socket;       //连接
        private void connectBtn_Click(object sender, EventArgs e)
        {
            try
            {
                //创建负责通信的socket
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //地址、端口
                IPAddress ip = IPAddress.Parse("192.166.2.48");
                int serverPort = Convert.ToInt32(5555);
                IPEndPoint port = new IPEndPoint(ip, serverPort);
                //连接到服务器
                socket.Connect(port);
                //启动接收数据线程
                Thread th = new Thread(receive);
                th.IsBackground = true;
                th.Start();
            }
            catch { }
        }   
         /// <summary>
        /// 发消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sendMsgBtn_Click(object sender, EventArgs e)
        {
            try
            {
                string txt = textBox1.Text;
                byte[] buffer = Encoding.ASCII.GetBytes(txt);//ascii编码
                socket.Send(buffer);
            }
            catch { }
        }

最后

以上就是体贴菠萝为你收集整理的C# WinForm实现TCP收发信息的全部内容,希望文章能够帮你解决C# WinForm实现TCP收发信息所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部