zoukankan      html  css  js  c++  java
  • 网络编程--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("
    Press 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

  • 相关阅读:
    FastReport合并多份报表为一份预览打印
    Delphi使用AcroPDF ActiveX显示PDF文件
    Delphi使用Zxing创建二维码
    TreeView和ListView数据库查询数据联动操作
    根据数据库查询结果动态创建控件(仿看板模式显示)
    GridView控件使用
    LayoutControl控件使用
    TreeListLookUpEdit控件使用
    Devexpress TreeList控件使用
    Asp.Net 5上传文件 (Core API方式)
  • 原文地址:https://www.cnblogs.com/Jaysonhome/p/12862980.html
Copyright © 2011-2022 走看看