C#tcp communication

Time:2022-5-3

C # based on socket client and server communication

Server

  • Server interface
  • C#tcp communication
  • Server code
public partial class FormMain : Form
    {
        private List<Socket> ClientSockets;
        private BindingList<string> ClientIPPorts;
        private Socket socketWatch;
        private Socket socketSend;// send out
        private bool IsStart;
        private Action<string> ShowMsgAction;
        private Action UpdateListViewDataAction;
        public FormMain()
        {
            InitializeComponent();
            ShowMsgAction += new Action<string>(ShowMsg);
            UpdateListViewDataAction += new Action(UpdateListViewData);
            ClientSockets = new List<Socket>();
            ClientIPPorts = new BindingList<string>();
            BindingSource bs = new BindingSource(); // Instantiate object
            bs. DataSource = ClientIPPorts; // Bind list < T > to BindingSource
            listBox1. DataSource = bs; // Bind BindingSource to the data source of the end user (control)
        }


        private void btn_start_Click(object sender, EventArgs e)
        {
            Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip = IPAddress.Any;
            //Create object port
            IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(tbox_port.Text));

            socketWatch. Bind(point);// Binding port number
            Showmsg ("message: listening succeeded!");
            socketWatch. Listen(100);// Number of clients allowed to connect
            //Create listening thread
            Thread thread = new Thread(Listen);
            thread.IsBackground = true;
            thread.Start(socketWatch);
            IsStart = true;
            ShowBtnState();

        }
        private void btn_stop_Click(object sender, EventArgs e)
        {
            socketWatch?.Close();
            IsStart = false;
            ShowBtnState();
            Showmsg ("message: stop listening!");
        }
        private void btn_send_Click(object sender, EventArgs e)
        {
            if (!IsStart) return;
            string info = rtbox_send.Text;
            if (info == "") return;
            int index = listBox1.SelectedIndex;
            if (index < 0) return;
            if (ClientSockets.Count <= index) return;
            socketSend = ClientSockets[index];
            Send(info);
        }


        void Listen(object o)
        {
            try
            {
                Socket socketWatch = o as Socket;
                while (IsStart)
                {
                    socketSend = socketWatch. Accept();// Waiting to receive client connection
                    ClientSockets.Add(socketSend);
                    ClientIPPorts.Add(socketSend.RemoteEndPoint.ToString());
                    this.BeginInvoke(UpdateListViewDataAction);
                    this. BeginInvoke (showmsgaction, socketsend. Remoteendpoint. Tostring() + ":" + "connection succeeded!");
                    //Start a new thread and execute the message receiving method
                    Thread r_thread = new Thread(Received);
                    r_thread.IsBackground = true;
                    r_thread.Start(socketSend);
                }
            }
            catch (Exception ex)
            {
                this. BeginInvoke (showmsgaction, "wait for exceptions in client listening:" + ex.message);
            }
        }
        /// <summary>
        ///The server keeps receiving messages from the client
        /// </summary>
        /// <param name="o"></param>
        void Received(object o)
        {
            try
            {
                Socket socketSend = o as Socket;
                if (!socketSend.Connected) return;
                while (IsStart)
                {
                    //After the client successfully connects to the server, the server receives the message sent by the client
                    byte[] buffer = new byte[1024 * 1024 * 3];
                    //Number of valid bytes actually received
                    int len = socketSend.Receive(buffer);
                    if (len == 0)
                    {
                        break;
                    }
                    string str = Encoding.UTF8.GetString(buffer, 0, len);
                    this.BeginInvoke(ShowMsgAction, socketSend.RemoteEndPoint + ":" + str);
                }
            }
            catch (Exception ex)
            {
                this. BeginInvoke (showmsgaction, "exception in receiving client content:" + ex.message);
            }
        }
        /// <summary>
        ///Send message
        /// </summary>
        /// <param name="str"></param>
        void Send(string str)
        {
            try
            {
                if (socketSend == null) return;
                byte[] buffer = Encoding.UTF8.GetBytes(str);
                socketSend.Send(buffer);
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
            }
           
        }
        private void ShowMsg(string msg)
        {
            string info = string.Format("{0}:{1}\r\n", DateTime.Now.ToString("G"), msg);
            rtbox_receive.AppendText(info);
        }
        private void ShowBtnState()
        {
            btn_start.Enabled = !IsStart;
            btn_stop.Enabled = IsStart;
        }
        /// <summary>
        ///Used to monitor whether the client is disconnected in real time
        /// </summary>

        private void timer1_Tick(object sender, EventArgs e)
        {
           
            if (ClientSockets.Count == 0) return;
            for (int i = ClientSockets.Count-1; i >= 0; i--)
            {
                if (!ClientSockets[i].Connected)
                {
                    ClientSockets.RemoveAt(i);
                    ClientIPPorts.RemoveAt(i);
                    this.BeginInvoke(UpdateListViewDataAction);
                }
                }
        }
        private void UpdateListViewData()
        {
            listBox1.DataSource = null;
            listBox1.DataSource = ClientIPPorts;
            //listBox1.Items.Clear();
            //for (int i = 0; i < ClientIPPorts.Count; i++)
            //{

            //}
        }
    }

client

  • Client interface

C#tcp communication

  • Client code
public partial class Form1 : Form
    {
        private Socket socketSend;
        private bool IsStart;
        private Action<string> ShowMsgAction;
        public Form1()
        {
            InitializeComponent();
            ShowMsgAction += new Action<string>(ShowMsg);
        }

        private void btn_connet_Click(object sender, EventArgs e)
        {
            try
            {
                //Create a client socket and obtain the remote IP and port number
                socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Parse(tbox_ip.Text);
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(tbox_port.Text));

                socketSend.Connect(point);
                Showmsg ("connection succeeded!");
                //Start a new thread and keep receiving messages from the server
                Thread c_thread = new Thread(Received);
                c_thread.IsBackground = true;
                c_thread.Start();
                IsStart = true;
                ShowBtnState();
            }
            catch (Exception ex)
            {
                Showmsg ("connection failure:" + ex.message);
            }
            
        }

        private void btn_disconnect_Click(object sender, EventArgs e)
        {
            if (socketSend.Connected)
            {
                socketSend.Close();
            }
            IsStart = false;
            ShowBtnState();
            Showmsg ("message: disconnect!");
        }

        private void btn_send_Click(object sender, EventArgs e)
        {
            if (!IsStart) return;
            string info = rtbox_send.Text;
            if (info == "") return;
            Send(info);
        }
        /// <summary>
        ///Receive thread
        /// </summary>
        private void Received()
        {
            while (IsStart)
            {
                try
                {
                    if (!socketSend.Connected) return;
                    byte[] buffer = new byte[1024 * 1024 * 3];
                    //Number of valid bytes actually received
                    int len = socketSend.Receive(buffer);
                    if (len == 0)
                    {
                        break;
                    }
                    string str = Encoding.UTF8.GetString(buffer, 0, len);
                    this.BeginInvoke(ShowMsgAction, socketSend.RemoteEndPoint + ":" + str);
                }
                catch (Exception ex)
                {
                    this.BeginInvoke(ShowMsgAction, ex.Message);
                }
            }
        }
        private void Send(string msg)
        {
            try
            {
                byte[] buffer = new byte[1024 * 1024 * 3];
                buffer = Encoding.UTF8.GetBytes(msg);
                socketSend.Send(buffer);
            }
            catch (Exception ex)
            {
                this.BeginInvoke(ShowMsgAction, ex.Message);
            }
        }
        private void ShowMsg(string msg)
        {
            string info = string.Format("{0}:{1}\r\n", DateTime.Now.ToString("G"), msg);
            rtbox_receive.AppendText(info);
        }
        private void ShowBtnState()
        {
            btn_connet.Enabled = !IsStart;
            btn_disconnect.Enabled = IsStart;
        }
    }