WinForm之Http网口通讯-服务端

WinForm之Http网口通讯-服务端

34WinForm之Http服务端UI

控件名称:
rtb_Receive_server
txt_Send_server
txt_Ip_server
txt_Port_server
btn_Start_server
btn_SendAscii_server
btn_SendUtf8_server
btn_Close_server
lb_ConnectState__server

lst_Online_Clients
        //  Http-Server(服务端):
        // 1:创建socket()
        // 2:设置IP和端口
        // 3. 绑定ip和端口
        // 4:listen()监听,确定能连接多少个客户端
        // 5:accept()函数接受客户端的连接
        // 6:接受数据
        // 7: 发送数据
        // 8:终止连接。

在这里插入图片描述

启动服务


        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Start_server_Click(object sender, EventArgs e)
        {
            // 1:创建socket()
            SocketSever = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // 2:设置IP和端口。
            IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(this.txt_Ip_server.Text), int.Parse(this.txt_Port_server.Text));

            try
            {
                // 3. 绑定ip和端口
                SocketSever.Bind(ipe);
            }
            catch (Exception ex)
            {
                MessageBox.Show("服务器开启失败:" + ex.Message);
                return;
            }
            // 4:listen(),确定能连接多少个客户端: 10 允许最多10个连接在队列中等待
            SocketSever.Listen(10);

            // 5.创建一个监听的线程

            Task.Run(new Action(() =>
            {
                AcceptClients();
            }));

            lb_ConnectState__server.Text = "启动成功";
            lb_ConnectState__server.BackColor = Color.Green;
            // 不可以再启动按钮
            btn_Start_server.Enabled = false;   
        }

监听客户端连接

        /// <summary>
        /// 监听客户端连接
        /// </summary>
        public void AcceptClients()
        {
            while (true)
            {
                // 5:accept()函数接受客户端的连接
                Socket socketClient = SocketSever.Accept();

                string client = socketClient.RemoteEndPoint.ToString();

                //  将客户端保存起来
                CurrentClientlist.Add(client, socketClient);

                
                UpdateOnlineClients(client, true);

                // 6:接受数据
                Task.Run(new Action(() =>
                {
                    ReceiveMessage(socketClient);
                }));
            }
        }

监听接收客户端数据


        /// <summary>
        /// 监听接收客户端数据
        /// </summary>
        /// <param name="socketClient"></param>
        private void ReceiveMessage(Socket socketClient)
        {
            while (true)
            {
                // 创建一个缓冲区

                byte[] buffer = new byte[1024 * 1024 * 10];

                // 数据长度
                int length = -1;

                string client = socketClient.RemoteEndPoint.ToString();

               
                try
                {
                    length = socketClient.Receive(buffer);
                }
                catch (Exception)
                {
                    UpdateOnlineClients(client, false);
                    MessageBox.Show(client + "下线了");
                    CurrentClientlist.Remove(client);
                    break;
                }

                if (length > 0)
                {
                    string msg = string.Empty;
                    // 以utf8的格式接受
                    msg = Encoding.UTF8.GetString(buffer, 0, length);

                    // 显示接受内容。需要使用Invoke,跨线程,跨UI
                    Invoke(new Action(() =>
                    {
                        rtb_Receive_server.AppendText(msg + "\n");
                    }));
                }
                else
                {
                    UpdateOnlineClients(client, false);
                    MessageBox.Show( client + "下线了");
                    CurrentClientlist.Remove(client);
                    break;
                }
            }
        }

更新在线客户列表

  /// <summary>
  /// 更新在线客户列表
  /// </summary>
  /// <param name="client"></param>
  /// <param name="add_or_delete"></param>
  public void UpdateOnlineClients(string client,bool add_or_delete)
  {
      Invoke(new Action(() =>
      {
          // 添加
          if (add_or_delete)
          {
              this.lst_Online_Clients.Items.Add(client);
          }
          // 删除
          else
          {
              foreach (string item in this.lst_Online_Clients.Items)
              {
                  if (item == client)
                  {

                      this.lst_Online_Clients.Items.Remove(item);
                      break;
                  }
              }
          }
      }));
  }

发送数据-Ascii

  /// <summary
  /// 发送数据Ascii
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void btn_SendAscii_server_Click(object sender, EventArgs e)
  {
      // 获取信息
      byte[] sendMsg = Encoding.ASCII.GetBytes(this.txt_Send_server.Text.Trim());

      // 对选中的客户端发送信息
      foreach (var item in this.lst_Online_Clients.SelectedItems)
      {
          //获取Socket对象
          string client = item.ToString();
          // 7: 发送数据
          CurrentClientlist[client]?.Send(sendMsg);
      }

      // 清空内容
      this.txt_Send_server.Clear();
  }

发送数据utf8

   /// <summary>
   /// 发送数据utf8
   /// </summary>
   /// <param name="sender"></param>
   /// <param name="e"></param>
   private void btn_SendUtf8_server_Click(object sender, EventArgs e)
   {
       // 获取信息
       byte[] sendMsg = Encoding.UTF8.GetBytes(this.txt_Send_server.Text.Trim());

       // 对选中的客户端发送信息
       foreach (var item in this.lst_Online_Clients.SelectedItems)
       {
           //获取Socket对象
           string client = item.ToString();
           // 7: 发送数据
           CurrentClientlist[client]?.Send(sendMsg);
       }

       // 清空内容
       this.txt_Send_server.Clear();

   }

断开连接

        /// <summary>
        /// 断开连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Close_server_Click(object sender, EventArgs e)
        {
            // 7:终止连接。
            SocketSever.Close();


            lb_ConnectState__server.Text = "停止服务";
            lb_ConnectState__server.BackColor = Color.Red;
            // 启动按钮
            btn_Start_server.Enabled = true;
        }

完整代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Messaging;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ReaLTaiizor.Forms;

namespace WinForm之Http网口通讯2
{
    public partial class Form1 : MaterialForm
    {


        //    Http-Client(客户端):
        //    1:创建通信套接字。
        //    2:设置服务器的IP和端口号。
        //    3:连接。
        //    4:发送数据。
        //    5:接受数据。
        //    6:关闭连接。


        //    1:创建通信套接字。
        public Socket SocketClient;

        public Form1()
        {
            InitializeComponent();
        }


        /// <summary>
        /// 连接服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Connect_Click(object sender, EventArgs e)
        {
            // 1:创建通信套接字。(确定为因特网,流式数据,tcp通讯)
            SocketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // 2.设置服务器的IP和端口号。(this,表示当前窗口,可以不加,加了更安全)
            IPEndPoint ip_port = new IPEndPoint(IPAddress.Parse(this.txt_Ip.Text.Trim()), int.Parse(this.txt_Port.Text.Trim()));

            // 3. 连接
            try
            {
                SocketClient.Connect(ip_port);
            }
            catch (Exception ex)
            {
                MessageBox.Show("连接服务器失败:" + ex.Message);
                return;
            }

            // 5:接受数据。
            //创建一个一直运行的监听的线程
            Task.Run(new Action(() =>
            {
                ReceiveMsg();
            }));


            lb_ConnectState_client.Text = "成功连接";
            lb_ConnectState_client.BackColor = Color.Green;

        }

        /// <summary>
        /// 以utf-8接受数据
        /// </summary>
        private void ReceiveMsg()
        {
            while (true)
            {
                // 创建一个缓冲区

                byte[] buffer = new byte[1024 * 1024 * 10];

                // 数据长度
                int length = -1;

                //  第四步:调用读写函数发送或者接收数据。
                try
                {
                    // 接受数据
                    length = SocketClient.Receive(buffer);
                }
                catch (Exception)
                {
                    break;
                }

                // 如果数据大于0,则解析
                if (length > 0)
                {
                    string msg = string.Empty;

                    msg = Encoding.UTF8.GetString(buffer, 0, length);

                    // 报错,因为跨线程,跨UI
                    // rtb_Receive.AppendText(msg);

                    // 需要使用Invoke
                    Invoke(new Action(() =>
                    {
                        rtb_Receive.AppendText(msg+"\n");
                    }));

                }
            }
        }

        /// <summary>
        /// 发送ASCII码数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SendAscii_Click(object sender, EventArgs e)
        {
            //转ASCII
            byte[] send = Encoding.ASCII.GetBytes(this.txt_Send.Text.Trim());

            // 发送数据(?. :如果对象为NULL,则不进行后面的获取成员方法的调用,直接返回NULL) 否则要写成if(SocketClient!=null) {调用}
            SocketClient?.Send(send);

            // 清空显示
            this.txt_Send.Clear();
        }

        private void btn_SendUtf8_Click(object sender, EventArgs e)
        {
            // 转utf8格式
            byte[] send = Encoding.UTF8.GetBytes(this.txt_Send.Text.Trim());

            // 发送数据
            SocketClient?.Send(send);

            // 清空显示
            this.txt_Send.Clear();
        }

        /// <summary>
        /// 关闭连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Close_Click(object sender, EventArgs e)
        {
            SocketClient?.Close();
            lb_ConnectState_client.Text = "断开连接";
            lb_ConnectState_client.BackColor = Color.Red;
        }




        //  Http-Server(服务端):
        // 1:创建socket()
        // 2:设置IP和端口
        // 3. 绑定ip和端口
        // 4:listen()监听,确定能连接多少个客户端
        // 5:accept()函数接受客户端的连接
        // 6:接受数据
        // 7: 发送数据
        // 8:终止连接。

        // 1:创建socket()
        public Socket SocketSever;

        // 创建接受客户端的字典(就是成对放的数组),发送数据给客户端的时候要用
        public Dictionary<string, Socket> CurrentClientlist = new Dictionary<string, Socket>();



        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Start_server_Click(object sender, EventArgs e)
        {
            // 1:创建socket()
            SocketSever = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // 2:设置IP和端口。
            IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(this.txt_Ip_server.Text), int.Parse(this.txt_Port_server.Text));

            try
            {
                // 3. 绑定ip和端口
                SocketSever.Bind(ipe);
            }
            catch (Exception ex)
            {
                MessageBox.Show("服务器开启失败:" + ex.Message);
                return;
            }
            // 4:listen(),确定能连接多少个客户端: 10 允许最多10个连接在队列中等待
            SocketSever.Listen(10);

            // 5.创建一个监听的线程

            Task.Run(new Action(() =>
            {
                AcceptClients();
            }));

            lb_ConnectState__server.Text = "启动成功";
            lb_ConnectState__server.BackColor = Color.Green;
            // 不可以再启动按钮
            btn_Start_server.Enabled = false;   
        }


        /// <summary>
        /// 监听客户端连接
        /// </summary>
        public void AcceptClients()
        {
            while (true)
            {
                // 5:accept()函数接受客户端的连接
                Socket socketClient = SocketSever.Accept();

                string client = socketClient.RemoteEndPoint.ToString();

                //  将客户端保存起来
                CurrentClientlist.Add(client, socketClient);

                
                UpdateOnlineClients(client, true);

                // 6:接受数据
                Task.Run(new Action(() =>
                {
                    ReceiveMessage(socketClient);
                }));
            }
        }

        /// <summary>
        /// 监听接收客户端数据
        /// </summary>
        /// <param name="socketClient"></param>
        private void ReceiveMessage(Socket socketClient)
        {
            while (true)
            {
                // 创建一个缓冲区

                byte[] buffer = new byte[1024 * 1024 * 10];

                // 数据长度
                int length = -1;

                string client = socketClient.RemoteEndPoint.ToString();

               
                try
                {
                    length = socketClient.Receive(buffer);
                }
                catch (Exception)
                {
                    UpdateOnlineClients(client, false);
                    MessageBox.Show(client + "下线了");
                    CurrentClientlist.Remove(client);
                    break;
                }

                if (length > 0)
                {
                    string msg = string.Empty;
                    // 以utf8的格式接受
                    msg = Encoding.UTF8.GetString(buffer, 0, length);

                    // 显示接受内容。需要使用Invoke,跨线程,跨UI
                    Invoke(new Action(() =>
                    {
                        rtb_Receive_server.AppendText(msg + "\n");
                    }));
                }
                else
                {
                    UpdateOnlineClients(client, false);
                    MessageBox.Show( client + "下线了");
                    CurrentClientlist.Remove(client);
                    break;
                }
            }
        }

        /// <summary>
        /// 更新在线客户列表
        /// </summary>
        /// <param name="client"></param>
        /// <param name="add_or_delete"></param>
        public void UpdateOnlineClients(string client,bool add_or_delete)
        {
            Invoke(new Action(() =>
            {
                // 添加
                if (add_or_delete)
                {
                    this.lst_Online_Clients.Items.Add(client);
                }
                // 删除
                else
                {
                    foreach (string item in this.lst_Online_Clients.Items)
                    {
                        if (item == client)
                        {

                            this.lst_Online_Clients.Items.Remove(item);
                            break;
                        }
                    }
                }
            }));
        }

        /// <summary
        /// 发送数据Ascii
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SendAscii_server_Click(object sender, EventArgs e)
        {
            // 获取信息
            byte[] sendMsg = Encoding.ASCII.GetBytes(this.txt_Send_server.Text.Trim());

            // 对选中的客户端发送信息
            foreach (var item in this.lst_Online_Clients.SelectedItems)
            {
                //获取Socket对象
                string client = item.ToString();
                // 7: 发送数据
                CurrentClientlist[client]?.Send(sendMsg);
            }

            // 清空内容
            this.txt_Send_server.Clear();
        }

        /// <summary>
        /// 发送数据utf8
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SendUtf8_server_Click(object sender, EventArgs e)
        {
            // 获取信息
            byte[] sendMsg = Encoding.UTF8.GetBytes(this.txt_Send_server.Text.Trim());

            // 对选中的客户端发送信息
            foreach (var item in this.lst_Online_Clients.SelectedItems)
            {
                //获取Socket对象
                string client = item.ToString();
                // 7: 发送数据
                CurrentClientlist[client]?.Send(sendMsg);
            }

            // 清空内容
            this.txt_Send_server.Clear();

        }

        /// <summary>
        /// 断开连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Close_server_Click(object sender, EventArgs e)
        {
            // 7:终止连接。
            SocketSever.Close();


            lb_ConnectState__server.Text = "停止服务";
            lb_ConnectState__server.BackColor = Color.Red;
            // 启动按钮
            btn_Start_server.Enabled = true;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值