码迷,mamicode.com
首页 > 其他好文 > 详细

网络编程--Socket

时间:2020-05-10 14:43:26      阅读:51      评论:0      收藏:0      [点我收藏+]

标签:errors   handle   compute   void   waiting   主机   array   ack   OLE   

单机测试:

服务端:

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

网络编程--Socket

标签:errors   handle   compute   void   waiting   主机   array   ack   OLE   

原文地址:https://www.cnblogs.com/Jaysonhome/p/12862980.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!