TCP / IP and socket chat rooms with class library source code sharing

Time:2022-5-8

TCP / IP and socket chat rooms with class library source code sharing

Recently, I came across a device that needs to do a network communication interaction with the customer’s software. Generally, our upper computer communicates with the device as a client. This time, I want to monitor the client as a server. Under this background, I consulted some big guys’ blogs and some materials. These are summarized into a simple server-side monitoring and client-side class library. I hope it will play a certain role for you. Of course, I still want to make a diary for myself. The following is the class library and some complete source code for testing the class library.

1. Communication class library

TCP / IP and socket chat rooms with class library source code sharingTCP / IP and socket chat rooms with class library source code sharing

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace TCP_DLL
{
    public class PSS_Server
    {
        private Dictionary cilentList = new Dictionary();
        private Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
        private Socket ConnCilent;
        /// 
        ///Create server
        /// 
        ///IP address
        ///Port
        public PSS_Server(string ip, int Port)
        {
            IPAddress _IP = IPAddress.Parse(ip);
            IPEndPoint endPoint = new IPEndPoint(_IP, Port);
            server.Bind(endPoint);
            server.Listen(20);
        }

        /// 
        ///Accept the connection request from the client
        /// 
        /// 
        /// 
        public bool Accept(ref string retn)
        {
            string info = "";
            try
            {
                ConnCilent = server. Accept();// Accept an incoming client
                if (ConnCilent != null)
                {
                    info = ConnCilent.RemoteEndPoint.ToString();
                    cilentList.Add(info, ConnCilent);
                    Retn = info + "access service succeeded!";
                }
                return true;
            }
            catch (Exception)
            {
                Retn = info + "access service failed!";
                return false;
            }
        }

        /// 
        ///Send message
        /// 
        /// 
        /// 
        public bool SendMsg(string str)
        {
            try
            {
                foreach (var item in cilentList)
                {
                    byte[] arrMsg = Encoding.UTF8.GetBytes(str);
                    item.Value.Send(arrMsg);
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// 
        ///Receive client messages
        /// 
        /// 
        /// 
        public bool Receive(object obj, ref string msg)
        {
            Socket ConnCilent1 = ConnCilent;
            IPEndPoint endPoint = null;
            try
            {
                byte[] arrMsg = new byte[1024 * 1024];
                int Len = ConnCilent1.Receive(arrMsg);
                if (Len != 0)
                {
                    msg = Encoding.UTF8.GetString(arrMsg, 0, Len);
                    endPoint = ConnCilent1.RemoteEndPoint as IPEndPoint;
                }
                return true;
            }
            catch (Exception)
            {
                if (endPoint!=null)
                {
                    cilentList.Remove(endPoint.ToString());
                }
                return false;
            }
        }
        /// 
        ///Close connection
        /// 
        public void Close()
        {
            try
            {
                server.Close();
                cilentList.Clear();
            }
            catch (Exception)
            {

            }
        }
    }

    public class PSS_Cilent
    {
        private Socket cilent = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
        /// 
        ///Create client
        /// 
        /// 
        /// 
        public bool Connect(string ip, int Port)
        {
            IPAddress _ip = IPAddress.Parse(ip);
            IPEndPoint endPoint = new IPEndPoint(_ip, Port);
            try
            {
                cilent.Connect(endPoint);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// 
        ///Close connection
        /// 
        public void Close()
        {
            try
            {
                cilent.Close();
            }
            catch (Exception)
            {

            }
        }
        /// 
        ///Receive message
        /// 
        /// 
        /// 
        public bool ReceiveMsg(ref string msg)
        {
            Socket _Cilent = cilent;
            try
            {
                //Defines the size of information received by the client
                byte[] arrlist = new byte[1024 * 1024];
                //Received message size
                int Len = cilent.Receive(arrlist);
                msg = Encoding.UTF8.GetString(arrlist, 0, Len);
                return true;
            }
            catch (Exception)
            {
                _Cilent.Close();
                return false;
            }
        }
        /// 
        ///Send message
        /// 
        /// 
        /// 
        public bool SenMsg(string msg)
        {
            try
            {
                byte[] arrmsg = Encoding.UTF8.GetBytes(msg);
                cilent.Send(arrmsg);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}

View Code

 

2. Server source code and interface

TCP / IP and socket chat rooms with class library source code sharingTCP / IP and socket chat rooms with class library source code sharing

using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ServerTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private TCP_DLL.PSS_Server Server;
        private void textBox3_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (Server.SendMsg(textBox3.Text).Equals(false))
                {
                    MessageBox. Show ("failed to send message!");
                    return;
                }
                textBox3.Clear();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string retn = "";
            Server = new TCP_DLL.PSS_Server(textBox1.Text, int.Parse(textBox2.Text));
            textBox4. Invoke(new Action(() => textBox4. Appendtext (datetime. Now + "\ R \ n" + "service creation completed, waiting for access..."+ "\r\n")));

            if (Server.Accept(ref retn).Equals(false))
            {
                MessageBox.Show(retn);
                return;
            }
            textBox4.Invoke(new Action(() => textBox4.AppendText(DateTime.Now + "\r\n" + retn + "\r\n")));


            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    string retn1 = "";
                    if (Server.Receive(ref retn).Equals(false))
                    {
                        MessageBox. Show ("abnormal message received!");
                        return;
                    }
                    textBox4.Invoke(new Action(() => textBox4.AppendText(DateTime.Now + "\r\n" + retn + "\r\n")));
                }
            });
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Server.Close();
        }
    }
}

View Code

2. Client interface and source code

TCP / IP and socket chat rooms with class library source code sharingTCP / IP and socket chat rooms with class library source code sharing

using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CilentTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private TCP_DLL.PSS_Cilent Cilent = new TCP_DLL.PSS_Cilent();

        private void textBox3_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode==Keys.Enter)
            {
                if (Cilent.SenMsg(textBox3.Text).Equals(false))
                {
                    MessageBox. Show ("sending message failed!!!");
                    return;
                }
                textBox3.Clear();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (Cilent.Connect(textBox1.Text,int.Parse(textBox2.Text)).Equals(false))
            {
                MessageBox. Show ("connection failed!!!");
                return;
            }
            textBox4. Invoke(new Action(() => textBox4. Appendtext (datetime. Now + "\ R \ n" + "create connection completed....."+ "\r\n")));
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    string retn = "";
                    if (Cilent.ReceiveMsg(ref retn).Equals(false))
                    {
                        MessageBox. Show ("abnormal message received!");
                        return;
                    }
                    textBox4.Invoke(new Action(() => textBox4.AppendText(DateTime.Now + "\r\n" + retn + "\r\n")));
                }
            });
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Cilent.Close();
        }
    }
}

View Code

3. Renderings