C# Socket编程 服务端与客户端(一)

首先介绍客户端,再介绍服务端

客户端:

在threadTestHeart中,首先根据IP等新建一个Socket heartSocket对象,接着将要传送的数据写进一个responseParam内,使用JsonConvert将要传输的数据Json化,最后将json以字节的形式通过Socket发送出去。在Main函数里一共新建了两个线程同时往同一个服务端发送数据(主要为了与之后我要讲的多线程并发联系,若简单起见,也可直接在Main函数内调用一下threadTestHeart方法即可),结果如代码后的图所示。


        static void Main(string[] args)
        {
            for (int i = 0; i < 2; i++)
            {
                new Thread(new ThreadStart(threadTestHeart)).Start();
            }
            Console.ReadKey();
        }
        public static void threadTestHeart()
        {
            IPAddress ip = IPAddress.Parse("192.168.5.83");
            IPEndPoint ipEnd = new IPEndPoint(ip, 3800);
            Socket heartSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            int socketCount = 0;
            heartSocket.Connect(ipEnd);           
            while (socketCount < 3)
            {
                Dictionary responseParam = new Dictionary();
                responseParam["Thread"] = Thread.CurrentThread.GetHashCode()+"";
                responseParam["MessageNo"] = socketCount.ToString();
                string bodyStr = JsonConvert.SerializeObject(responseParam);
                byte[] body = Encoding.UTF8.GetBytes(bodyStr);
                string packStr = string.Format("HEAD{0:000}", body.Length) + bodyStr;
                heartSocket.Send(Encoding.UTF8.GetBytes(packStr));
                Console.WriteLine("Socket NO: "+Thread.CurrentThread.GetHashCode()+ "  MessageNo "+socketCount);
                socketCount++;
                Thread.Sleep(500);
            }
            heartSocket.Close();
        }

客户端结果:

C# Socket编程 服务端与客户端(一)_第1张图片

服务端:

与客户端类似,不过多了几行检测Socket是否有连接的代码。

 internal SocketServer()
        {
            Socket m_svrSock = null;
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 3800);
            m_svrSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            m_svrSock.Bind(endPoint);
            m_svrSock.Listen(100);
            Console.WriteLine("Listen Up...");
            int customerCount = 1;
            while (true)
            {
                Socket client;
                client = m_svrSock.Accept();
                if (!client.Poll(-1, SelectMode.SelectRead))
                {
                    continue;
                }
                Console.WriteLine("Customer:" + customerCount);
                customerCount++;
                int lineCount = 0;
                byte[] receive = new byte[7];
                while (true)
                {
                    Thread.Sleep(500);
                    if (!client.Poll(-1, SelectMode.SelectRead))
                    {
                        lineCount++;
                        continue;
                    }
                    if (client.Receive(receive, 7, SocketFlags.None) == 0)
                    {
                        Console.WriteLine("no data here!The customer has closed his client!");
                        break;
                    }
                    string lengthStr = Encoding.UTF8.GetString(receive, 4, 3);
                    int length = int.Parse(lengthStr);
                    byte[] receiveBody = new byte[length];
                    client.Receive(receiveBody, length, SocketFlags.None);
                    Console.WriteLine("line:" + lineCount + Encoding.UTF8.GetString(receiveBody));
                    lineCount++;
                }
            }
        }
服务端结果如图:

C# Socket编程 服务端与客户端(一)_第2张图片


客户端与服务端的结果虽然看似简单,但里面却体现出了很多Socket编程值得注意的地方,细细体会,其中服务端没有用到多线程与并发,只是简单的将每个客户端链接的数据显示,我将在之后做出修改,到时比较区别,细细体会,嘿嘿。


参考:MSDN的Socket类

你可能感兴趣的:(C#,c#,socket,多线程,线程,并发)