Socket通信方面

Posted nanguoyezi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Socket通信方面相关的知识,希望对你有一定的参考价值。

服务端

Console.WriteLine("Starting ");
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listener.Bind(new IPEndPoint(IPAddress.Any, 2112));
            listener.Listen(10);
            while (true)
            {
                Console.WriteLine("wait for...");
                Socket socket = listener.Accept();
                string receivedValue = string.Empty;

                while (true)
                {
                    byte[] receiveBytes = new byte[1024];
                    int numBytes = socket.Receive(receiveBytes);
                    Console.WriteLine("Receiving");

                    receivedValue += Encoding.ASCII.GetString(receiveBytes, 0, numBytes);
                    if (receivedValue.IndexOf("[FINAL]") > -1)
                    {
                        break;
                    }
                }

                Console.WriteLine("Receiver value:{0}", receivedValue);
                string replyValue = "Message successfully received.";
                byte[] replyMessage = Encoding.ASCII.GetBytes(replyValue);
                socket.Send(replyMessage);
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
            }
            listener.Close();

  客户端

byte[] receivedBytes = new byte[1024];
            //IPHostEntry iPHost = new IPHostEntry();
            //iPHost.HostName = "127.0.0.1";
            //IPAddress iPAddress = iPHost.AddressList[0];
            IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2112);
            Console.WriteLine("Starting");

            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(iPEndPoint);
            Console.WriteLine("Successfully conneted to{0}", socket.RemoteEndPoint);

            string sendingMessage = "Hello World Socket Test";
            Console.WriteLine("Creating Message: Hello World Socket Test");
            byte[] forwardMessage = Encoding.ASCII.GetBytes(sendingMessage + "[FINAL]");
            socket.Send(forwardMessage);
            int totalBytesReceived = socket.Receive(receivedBytes);
            Console.WriteLine("Message provided from server: {0}", Encoding.ASCII.GetString(receivedBytes, 0, totalBytesReceived));

            socket.Shutdown(SocketShutdown.Both);
            socket.Close();

            Console.ReadLine();

  

以上是关于Socket通信方面的主要内容,如果未能解决你的问题,请参考以下文章

socket库:Python实现UDP客户和服务器通信

socket库:Python实现UDP客户和服务器通信

通过 c# 与 socket.io 服务器通信

小练习:用socket实现Linux和Windows之间的通信

Jmeter:使用TCP取样器与socket接口进行简单通信

Android网络应用之Socket