小言_互联网的博客

c#客户端与服务端通信demo

222人阅读  评论(0)


基础的介绍在我上一个博客哦,
https://blog.csdn.net/weixin_43482965/article/details/116404120

1 效果图:

2 项目:

c#窗体程序,有连个窗体

  • FrmServer(服务端窗体)
  • FrmClient(客户端窗体)

2.1 FrmServer(服务端窗体)


代码:

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

namespace Socket_test
{
   
    public partial class FrmServer : Form
    {
   
        public FrmServer()
        {
   
            InitializeComponent();
            //委托注册
            myRcvMsg = RecMsg;
            myAddOnline = AddOnline;
        }

        #region 属性
   
        //创建套接字
        Socket sock = null;
        //创建负责监听客户端连接的线程
        Thread threadListen = null;
        //声明委托,添加消息
        Action<string> myRcvMsg = null;
        //委托,管理客户端在线列表
        Action<string, bool> myAddOnline = null;
        //创建URL与Socket的字典集合
        Dictionary<string, Socket> DicSocket = new Dictionary<string, Socket>();
        #endregion

        #region 方法
        //添加到消息框里面
        private void RecMsg(string str)
        {
   
            this.txt_Rcv.AppendText(str + Environment.NewLine);
        }
        /// <summary>
        /// 监听线程
        /// </summary>
        private void ListenConnecting(object obj)
        {
   
            while (true)
            {
   
                //一旦监听到一个客户端的连接,将会创建一个与该客户端连接的套接字
                Socket sockClient = sock.Accept();
                string client = sockClient.RemoteEndPoint.ToString();
                //往集合里添加
                DicSocket.Add(client, sockClient);
                //客户端列表中添加
                Invoke(myAddOnline, client, true);
                //消息里面添加内容
                Invoke(myRcvMsg, client + "上线了!");
                //开启接受线程
                Thread thr = new Thread(ReceiveMsg);
                thr.IsBackground = true;
                thr.Start(sockClient);

            }
        }
        /// <summary>
        /// 接收线程
        /// </summary>
        /// <param name="sockClient"></param>
        private void ReceiveMsg(object sockClient)
        {
   
            Socket sckclient = sockClient as Socket;
            while (true)
            {
   
                //定义一个2M缓冲区
                byte[] arrMsgRec = new byte[1024 * 1024 * 2];

                int length = -1;

                try
                {
   
                    length = sckclient.Receive(arrMsgRec);
                }
                catch (Exception)
                {
   
                    string str = sckclient.RemoteEndPoint.ToString();
                    Invoke(myRcvMsg, str + "下线了!");
                    //从列表中移除URL
                    Invoke(myAddOnline, str, false);
                    DicSocket.Remove(str);
                    break;
                }

                if (length == 0)
                {
   
                    string str = sckclient.RemoteEndPoint.ToString();
                    Invoke(myRcvMsg, str + "下线了!");
                    //从列表中移除URL
                    Invoke(myAddOnline, str, false);
                    DicSocket.Remove(str);
                    break;
                }
                else
                {
   
                  
                        string strMsg = Encoding.UTF8.GetString(arrMsgRec);
                        string Msg ="[接收] " + sckclient.RemoteEndPoint.ToString() + "     " + strMsg + "\r\n";
                        Invoke(myRcvMsg, Msg);
                }
            }
        }
        /// <summary>
        /// 管理客户端在线列表
        /// </summary>
        /// <param name="url"></param>
        /// <param name="bl"></param>
        private void AddOnline(string url, bool bl)
        {
   
            if (bl)
            {
   
                this.lbOnline.Items.Add(url);
            }
            else
            {
   
                this.lbOnline.Items.Remove(url);
            }
        }

        #endregion
        //开启服务
        private void btn_StartServer_Click(object sender, EventArgs e)
        {
   
            //创建负责监听的套接字,注意其中参数:IPV4 字节流 TCP
            sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress address = IPAddress.Parse(this.txt_IP.Text.Trim());
            //根据IPAddress以及端口号创建IPE对象
            IPEndPoint endpoint = new IPEndPoint(address, int.Parse(this.txt_Port.Text.Trim()));
            try
            {
   
                //尝试绑定
                sock.Bind(endpoint);
                Invoke(myRcvMsg, "服务器开启成功!");
                MessageBox.Show("开启服务成功!", "打开服务");
            }
            catch (Exception ex)
            {
   
                MessageBox.Show("开启服务失败" + ex.Message, "打开服务");
                return;
            }

            sock.Listen(10);
            threadListen = new Thread(ListenConnecting);
            threadListen.IsBackground = true;
            threadListen.Start();
            this.btn_StartServer.Enabled = false;
        }
         //打开客户端
        private void btn_Client_Click(object sender, EventArgs e)
        {
   
           
            FrmClient f1 = new FrmClient();
            f1.Show();
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SendToSingle_Click(object sender, EventArgs e)
        {
   
            string StrMsg = this.txt_Send.Text.Trim();
            byte[] arrMsg = Encoding.UTF8.GetBytes(StrMsg);

            //byte[] arrSend = new byte[arrMsg.Length + 1];
            //arrSend[0] = 0;
            //Buffer.BlockCopy(arrMsg, 0, arrSend, 1, arrMsg.Length);
            if (this.lbOnline.SelectedItems.Count == 0)
            {
   
                MessageBox.Show("请选择你要发送的对象!", "发送提示");
                return;
            }
            else
            {
      //遍历选择的客户端
                foreach (string item in this.lbOnline.SelectedItems)
                {
   
                    //send的方法
                    DicSocket[item].Send(arrMsg);
                    string Msg = "[发送]     " + item + "     " + StrMsg + "\r\n";
                    //添加消息里面
                    Invoke(myRcvMsg, Msg);
                }
            }
        }
        //群发
        private void btn_SendToAll_Click(object sender, EventArgs e)
        {
   
            string StrMsg = this.txt_Send.Text.Trim();
            byte[] arrMsg = Encoding.UTF8.GetBytes(StrMsg);
            foreach (string item in this.DicSocket.Keys)
            {
   
                DicSocket[item].Send(arrMsg);

                string Msg = "[发送]     " + item + "     " + StrMsg + "\r\n";

                Invoke(myRcvMsg, Msg);
            }
            Invoke(myRcvMsg, "[群发]     群发完毕!" + "\r\n");
        }

      
      
    }
}

2.1 FrmClient(客户端窗体)


代码

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

namespace Socket_test
{
   
    public partial class FrmClient : Form
    {
   
        public FrmClient()
        {
   
            InitializeComponent();
        }
        //Socket对象
        Socket sockClient = null;

        //接收线程
        Thread thrClient = null;

        //运行标志位
        private bool IsRunning = true;
        private void btn_Connect_Click(object sender, EventArgs e)
        {
   
            IPAddress address = IPAddress.Parse(this.txt_IP.Text.Trim());
            IPEndPoint Ipe = new IPEndPoint(address, int.Parse(this.txt_Port.Text.Trim()));
            sockClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
   
                this.txt_Rcv.AppendText("与服务器连接中......" +"\r\n");
                //Connect方法
                sockClient.Connect(Ipe);
            }
            catch (Exception ex)
            {
   
                MessageBox.Show("连接失败" + ex.Message, "建立连接");
                return;
            }

            this.txt_Rcv.AppendText("与服务器连接成功" + "\r\n");
            this.btn_Connect.Enabled = false;

            thrClient = new Thread(ReceiceMsg);
            thrClient.IsBackground = true;
            thrClient.Start();
        }
        #region 接收消息
        /// <summary>
        /// 接收消息
        /// </summary>
        private void ReceiceMsg()
        {
   
            while (IsRunning)
            {
   
                //定义一个2M缓冲区
                byte[] arrMsgRec = new byte[1024 * 1024 * 2];

                int length = -1;

                try
                {
   
                    //接收
                    length = sockClient.Receive(arrMsgRec);
                }
                catch (SocketException)
                {
   
                    break;
                }
                catch (Exception ex)
                {
   
                    Invoke(new Action(() => this.txt_Rcv.AppendText("断开连接" + ex.Message + Environment.NewLine)));
                    break;
                }

                if (length > 0)
                {
   
                    
                 
                         string strMsg = Encoding.UTF8.GetString(arrMsgRec);
                         string Msg = "\r\n" + "[接收]     " + strMsg + "\r\n";
                         Invoke(new Action(() => this.txt_Rcv.AppendText(Msg+Environment.NewLine)));
              
                   
                }
            }
        }

        #endregion

        private void btn_Send_Click(object sender, EventArgs e)
        {
   
            string strMsg = "来自" + this.txt_Name.Text.Trim() + ":  " + this.txt_Send.Text.Trim();
            byte[] arrMsg = Encoding.UTF8.GetBytes(strMsg);
            sockClient.Send(arrMsg);
            Invoke(new Action(() => this.txt_Rcv.AppendText("[发送]     " + this.txt_Send.Text.Trim() +"\r\n")));
        }

        private void FrmClient_Load(object sender, EventArgs e)
        {
   
            txt_Name.Text = "客户端" + DateTime.Now.GetHashCode();
        }

        private void FrmClient_FormClosing(object sender, FormClosingEventArgs e)
        {
   
            IsRunning = false;
            sockClient.Close();
        }
    }
}


转载:https://blog.csdn.net/weixin_43482965/article/details/116405984
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场