网络编程--Socket

单机测试:

服务端:

public class SynchronousSocketListener
{
    // Incoming data from the client.  
    public static string data = null;
    public static void StartListening()
    {
        // Data buffer for incoming data.  
        byte[] bytes = new Byte[1024];
        // Establish the local endpoint for the socket.  
        // Dns.GetHostName returns the name of the
        // host running the application.  
        IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);   
//1.创建 
        // Create a TCP/IP socket.  
        Socket listener = new Socket(ipAddress.AddressFamily,
            SocketType.Stream, ProtocolType.Tcp);

        // Bind the socket to the local endpoint and
        // listen for incoming connections.  
        try
        {
//2.绑定且监听
            listener.Bind(localEndPoint);
            listener.Listen(10);

            // Start listening for connections.  
            while (true)
            {
                Console.WriteLine("Waiting for a connection...");
                // Program is suspended while waiting for an incoming connection. 
//3.循环接收ing,
                Socket handler = listener.Accept();
                data = null;
//4.收发消息
                // An incoming connection needs to be processed.  
                while (true)
                {
                    int bytesRec = handler.Receive(bytes);
                    //data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    data += Encoding.UTF8.GetString(bytes, 0, bytesRec);
                    if (data.IndexOf("<EOF>") > -1)
                    {
                        break;
                    }
                }

                // Show the data on the console.  
                Console.WriteLine("收到请求 : {0}", data);

                // Echo the data back to the client.  
                byte[] msg = Encoding.UTF8.GetBytes("中心收到了你的问题--"+data);

                handler.Send(msg);
//5.停止且关闭  
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        Console.WriteLine("\nPress ENTER to continue...");
        Console.Read();
    }

客户端:

public static void StartClient()
    {
        // Data buffer for incoming data.  
        byte[] bytes = new byte[1024];

        // Connect to a remote device.  
        try
        {
            // Establish the remote endpoint for the socket.  
            // This example uses port 11000 on the local computer.  
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);

//1.创建        
            // Create a TCP/IP  socket.  
            Socket sender = new Socket(ipAddress.AddressFamily,
                SocketType.Stream, ProtocolType.Tcp);

//2.连接       
            // Connect the socket to the remote endpoint. Catch any errors.  
            try
            {
                sender.Connect(remoteEP);

                Console.WriteLine("Socket connected to {0}",
                    sender.RemoteEndPoint.ToString());

                // Encode the data string into a byte array.  
                //byte[] msg = Encoding.ASCII.GetBytes("客户端:This is a test<EOF>");
                byte[] msg = Encoding.UTF8.GetBytes("中心,你好吗?<EOF>");

//3.向对方发送消息            
                // Send the data through the socket.  
                int bytesSent = sender.Send(msg);

//4.接收对方消息            
                //同步-堵塞,如果没有接收到消息将不会往下执行
                //Receive the response from the remote device.  
                int bytesRec = sender.Receive(bytes);
                Console.WriteLine("收到响应 = {0}",
                    Encoding.UTF8.GetString(bytes, 0, bytesRec));
                 
                
                //当继续send和receive会提示主机中止了连接!!
                //sender.Send(msg);
                //int bytesRec2 = sender.Receive(bytes);
                //Console.WriteLine("收到响应2222 = {0}",
                //    Encoding.UTF8.GetString(bytes, 0, bytesRec2));

//5.停止且关闭            
                // Release the socket.  
                sender.Shutdown(SocketShutdown.Both);
                sender.Close();
                 
            }
            catch (ArgumentNullException ane)
            {
                Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
            }
            catch (SocketException se)
            {
                Console.WriteLine("SocketException : {0}", se.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception : {0}", e.ToString());
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

运行:

丢失连接:

Socket 代码示例-docs.microsoft

posted @ 2020-05-10 13:25  天山鸟  阅读(127)  评论(0编辑  收藏  举报