Simple socket examples and principles (including source code)

What is a socket?

The so-called socket is usually also called "socket", which is used to describe the IP address bai and port, and is the handle of a communication chain. The application usually sends a request to the network or responds to a network request through a "socket".

 

Socket connection process:

Socket is divided into server and client, here we use serverSocket and clientSocket to represent

Server monitoring: The server-side socket does not actively specify the client socket, but is in a state of waiting for monitoring, real-time monitoring of the network status.

Client request: The client clientSocket sends a connection request, and the target is the serverSocket of the server. So clientSocket must know the ip and port number of serverSocket

Connection confirmation: When the server socket monitors or receives a connection request from the client socket, the server responds to the client's request, suggesting a new socket and sending the server socket to the client. Once the client confirms the connection, the connection is established.

 

The following figure briefly illustrates the linking process:

 

For details, please refer to the simple code (here the source code has been put into the "Ink Direct" official account, just reply to the socket source code ):

The source code is wpf, because the project source code is not easy to split and package, so an example was built, if you don’t understand here, you can download the source code and study it carefully.

//Server

 Thread threadWatch = null;
 Socket Mysocket = null;
 ListBox ClientListboxs = null;
 //接受缓存
  byte[] arrMsgRec = new byte[1024 * 1024 * 2];
 Socket policy = null;
 Dictionary<string, Socket> SoketList = new Dictionary<string, Socket>();
 Thread threadRece = null;
   private void StartSocket()
        {
            //创建监听套接字
            Mysocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //获取ip对象
            IPAddress address = IPAddress.Parse("192.168.3.57");
            //创建IP和端口
            IPEndPoint endpoint = new IPEndPoint(address, int.Parse("4502"));
            Mysocket.Bind(endpoint);//绑定EndPoint对像 
            //监听队列长度
            Mysocket.Listen(10);
            threadWatch = new Thread(WatchConnection);
            threadWatch.IsBackground = true;
            threadWatch.Start();
        }
        
   // 监听新客户端请求    
 private void WatchConnection()
        {
            showMessage("等待客户连接");
            while (true)
            {
                policy = Mysocket.Accept();
                Socket policynew = policy;
                showMessage("连接成功");

                ListBox ClientListbox = ClientListboxs;
                ClientListbox.Dispatcher.Invoke(new Action(() => { ClientListbox.Items.Add(policynew.RemoteEndPoint.ToString()); }));
                SoketList.Add(policynew.RemoteEndPoint.ToString(), policy);//为新建连接创建新的socket
                if (threadRece == null)
                {
                    threadRece = new Thread(Rece);
                    threadRece.IsBackground = true;
                    threadRece.Start();
                }
            }
        }

This thread has always existed. The main task is to monitor whether there is a connection between Client and Server. If the connection is successful, another thread "Rece" will be opened. In this thread, it is mainly to get the character data processing, including receiving data and sending data.

  private void Rece()
        {
            while (true)
            {
                try
                {
                    int strlong = policy.Receive(arrMsgRec);
                    byte[] message = arrMsgRec;
                    byte[] lin = arrMsgRec.Skip(2).Take(strlong - 4).ToArray();
                    string strMsgRec = System.Text.Encoding.UTF8.GetString(lin, 0, strlong - 4);//实际转换的字节长度为内容长度
                    showMessage(strMsgRec);
                }
                catch (Exception)
                {
                    
                }
            }
        }

        private void showMessage(string msg)
        {
            Action action = () => MsgContent.AppendText(msg + "\r\n");
            if (System.Threading.Thread.CurrentThread !=
        MsgContent.Dispatcher.Thread)
            {
                MsgContent.Dispatcher.Invoke
                    (System.Windows.Threading.DispatcherPriority.Normal,
                    action);
            }
            else
            {
                action();
            }
        }

The following is to send data to the client

 private void send(object sender, RoutedEventArgs e)
        {
            senddate = System.DateTime.Now;
            var TELH = (char)0x02 + (char)0x30;//头部(无需照搬,测试用的)
            var TELF = (char)0x5F + (char)0x03;//尾部(无需照搬,测试用的)
            var Content = MsgContext.Text;
            var msg = TELH + Content + TELF;
            byte[] btMsg = System.Text.Encoding.UTF8.GetBytes(msg);
            policy.Send(btMsg);
            showMessage("发送:" +  MsgContext.Text);
        }

 Note here: In fact, the data transmitted in TCP/IP should be in bytes. For example, to transmit 50 double data is to transmit an array of 400 bytes

//Client

Socket Mysocket = null;
byte[] arrMsgRec = new byte[1024 * 1024 * 2];
   public void client()
        {
            Mysocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //获取ip对象
            IPAddress address = IPAddress.Parse("192.168.3.57");
            //创建IP和端口
            IPEndPoint endpoint = new IPEndPoint(address, int.Parse("4502"));
            Mysocket.Connect(endpoint);
            Thread threadWatch = new Thread(ReceiveMsg);
            //threadWatch.IsBackground = true;
            threadWatch.Start();
        }

From the server source code, you can see that the composition of the message is composed of header (two bytes) + content + tail (two bytes), so if you want to get the content here, skip the header and take the total length -4 part.

 public void ReceiveMsg()
        {
            while (true)
            {
                int strlong = Mysocket.Receive(arrMsgRec);
                byte[] message = arrMsgRec;
                byte[] lin = arrMsgRec.Skip(2).Take(strlong - 4).ToArray();
                string strMsgRec = System.Text.Encoding.UTF8.GetString(lin, 0, strlong - 4);//实际转换的字节长度为内容长度
                showMessage(strMsgRec);
            }
        }

//send

 public void Sends()
        {
           
            var TELH = (char)0x02 + (char)0x30;//头部
            var  TELF = (char)0x5F + (char)0x03;//尾部
            var Content = MsgSend.Text;
            var msg = TELH + Content + TELF;
            byte[] btMsg = System.Text.Encoding.UTF8.GetBytes(msg);
            Mysocket.Send(btMsg);
            showMessage("发送:" + MsgSend.Text);

        }

Display data on the control

 private void showMessage(string msg)
        {
            Action action = () => MsgContent.AppendText(msg + "\r\n");
            if (System.Threading.Thread.CurrentThread !=
        MsgContent.Dispatcher.Thread)
            {
                MsgContent.Dispatcher.Invoke
                (System.Windows.Threading.DispatcherPriority.Normal,
                action);
            }
            else
            {
                action();
            }

        }

 Here, a simple socket communication is completed, and the effect is as follows:

There are many practical uses of sockets. Here I mainly use them for communication between programs and devices. For example, qq uses sockets for communication, and browsers and servers also use sockets for communication, but the transmission of http packets in the http protocol is available. Interested friends can study by themselves

Here is a detailed blog post http://www.jytek.com/seesharpsocket

Those who are interested can pay attention to " Ink Direct ", there are many free programming materials to receive~

 

Guess you like

Origin blog.csdn.net/huxinyu0208/article/details/112758950