C# realizes the simple sending and receiving function of socket

Due to the needs of the project, it is necessary to use sockets to send and receive messages, so there are the following codes, which should be saved first, so that they cannot be restored after actual development in the future.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {

        private static byte[] result = new byte[1024];
        private static int myProt = 8885; //Port
        private static Socket serverSocket;
        private static int ConnectCount = 0;
        private static int MaxConnectCount = 3;
        private static List<string> messageList = new List<string>();
        static object objToLock = new object();

        static void Main(string[] args)
        {

            //Server IP address
            IPAddress ip = IPAddress.Parse("ip");
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(new IPEndPoint(ip, myProt)); //Bind IP address: port
            serverSocket.Listen(2); //Set up to 10 queued connection requests
            Console.WriteLine("Start listening {0} succeeded", serverSocket.LocalEndPoint.ToString());
            new Thread(ListenClientConnect).Start();
            Console.ReadLine();

        }

        /// <summary>
        /// Listen for client connections
        /// </summary>
        private static void ListenClientConnect()
        {
            while (true)
            {
                Socket clientSocket = serverSocket.Accept();
                //clientSocket.Send(Encoding.UTF8.GetBytes("string### is a joke again!mdzz"));
                //Console.WriteLine("123");

                //FileStream fs = new FileStream("D:/23.jpg", FileMode.Open);
                //BinaryReader br = new BinaryReader(fs);
                //Byte[] byData = br.ReadBytes((int)fs.Length);
                //fs.Close();

                //Console.WriteLine("2");

                //clientSocket.Send(byData);

                //Console.WriteLine("3");
                if (ConnectCount < MaxConnectCount)
                {
                    clientSocket.Send(Encoding.UTF8.GetBytes("Come on again!mdzz"));
                    Thread receiveThread = new Thread(ReceiveMessage);
                    receiveThread.Start(clientSocket);
                }
                else
                {
                    clientSocket.Send(Encoding.UTF8.GetBytes("Exceeded the maximum number of connections"));
                    clientSocket.Close();
                }

            }
        }

        /// <summary>
        /// Receive message
        /// </summary>
        /// <param name="clientSocket"></param>
        private static void ReceiveMessage(object clientSocket)
        {

            if (ConnectCount < MaxConnectCount)
            {
                ConnectCount++;
                Socket myClientSocket = (Socket)clientSocket;
                int receiveNumber = -1;
                string userName = "";

                while(userName.Equals(""))
                {
                    Console.WriteLine("Waiting for username");
                    receiveNumber = myClientSocket.Receive(result);
                    if (receiveNumber > 0)
                    {
                        userName = Encoding.UTF8.GetString(result, 0, receiveNumber);
                        Console.WriteLine("Get user name:" + userName);
                        //send data
                        myClientSocket.Send(Encoding.UTF8.GetBytes("Receiver account:" + userName));
                    }
                }

                int count = 0;
                Boolean filestar = false;
                MemoryStream ms = new MemoryStream();
                while (true)
                {   
                    try
                    {

                        if (myClientSocket.Poll(-1, SelectMode.SelectRead))
                        {
                            //Receive data through clientSocket
                            receiveNumber = myClientSocket.Receive(result);
                            if (receiveNumber > 0)
                            {
                                
                                if (Encoding.UTF8.GetString(result, 0, receiveNumber).IndexOf("filestar")==0)
                                {
                                    Console.WriteLine("Receive client {0} message {1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(result, 0, receiveNumber));
                                    filestar = true;
                                }

                                if (filestar)
                                {
                                    if (Encoding.UTF8.GetString(result, 0, receiveNumber).IndexOf("fileend") == 0)
                                    {
                                        Console.WriteLine("Receive client {0} message {1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(result, 0, receiveNumber));
                                        FileStream fs = new FileStream("D:\\test.jpg", FileMode.OpenOrCreate);
                                        BinaryWriter w = new BinaryWriter(fs);
                                        w.Write(ms.ToArray());
                                        fs.Close();
                                        myClientSocket.Send(Encoding.UTF8.GetBytes("fielLength:" + ms.Length));
                                        ms.Dispose();
                                        count = 0;
                                    }
                                    else if(count==1)
                                    {
                                        ms.Write(result, 0, receiveNumber);
                                    }else
                                    {
                                        count++;
                                    }
                                }

                                //send data
                                //myClientSocket.Send(Encoding.UTF8.GetBytes("Receive complete, data feedback port: " + myClientSocket.RemoteEndPoint.ToString()));
                            }
                            else if (receiveNumber==0)
                            {
                                //socket connection is disconnected
                                Console.WriteLine("Disconnect");
                                myClientSocket.Close();
                                ConnectCount--;
                                break;
                            }

                        }
                        else
                        {
                            //socket connection is disconnected
                            Console.WriteLine("Disconnect 123");
                            myClientSocket.Close();
                            ConnectCount--;
                            break;
                        }

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        myClientSocket.Shutdown(SocketShutdown.Both);
                        break;
                    }

                }
            }
            else
            {
                Console.WriteLine("Exceeded maximum link client");
            }

        }

    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326400323&siteId=291194637