• C # socket 实例


    同步客户端存储示例

    下面的示例程序创建连接到服务器的客户端。             客户端使用一个同步套接字生成,因此,客户端应用程序的执行挂起,直到服务器返回响应。  应用程序将字符串发送到服务器并显示在控制台的服务器返回的字符串。

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    
    public class SynchronousSocketClient {
    
        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.Resolve(Dns.GetHostName())
            //Dns是一个静态类,它从 Internet 域名系统(DNS) 检索关于特定主机的信息。
            //Dns.GetHostName()获取本地计算机的主机名。
            //Dns.Resolve() 将 DNS 主机名或 IP 地址解析为 IPHostEntry实例。
            //类IPHostEntry  为 Internet 主机地址信息提供容器类。
    
                IPAddress ipAddress = ipHostInfo.AddressList[0];//提供网际协议 (IP) 地址。
                IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);//将网络端点表示为 IP 地址和端口号。
    
                // Create a TCP/IP  socket.
                Socket sender = new Socket(AddressFamily.InterNetwork, 
                    SocketType.Stream, ProtocolType.Tcp );
            //InterNetwork   IP 版本 4 的地址。
            //Stream 支持可靠、双向、基于连接的字节流,而不重复数据,也不保留边界。  
            //    此类型的 Socket 与单个对方主机通信,并且在通信开始之前需要建立远程主机连接。  
            //    Stream使用传输控制协议 (Tcp) ProtocolType和 InterNetworkAddressFamily。  
                // 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>");
    
                    // Send the data through the socket.
                    int bytesSent = sender.Send(msg);
    
                    // Receive the response from the remote device.
                    int bytesRec = sender.Receive(bytes);
                    Console.WriteLine("Echoed test = {0}",
                        Encoding.ASCII.GetString(bytes,0,bytesRec));
    
                    // 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());
            }
        }
        
        public static int Main(String[] args) {
            StartClient();
            return 0;
        }
    }
    

     同步服务器端存储示例

    下面的示例程序创建接收来自客户端的连接请求的服务器。             服务器使用一个同步套接字生成,因此,服务器应用程序的执行挂起,它在等待从客户端时的连接。  应用程序收到来自客户端的字符串,在控制台上显示字符串,然后回显该字符串返回给客户端。  从客户端的字符串必须包含字符串“<EOF>”用于通知消息的结尾。

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    
    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.Resolve(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
    
            // Create a TCP/IP socket.
            Socket listener = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp );
    
            // Bind the socket to the local endpoint and 
            // listen for incoming connections.
            try {
                listener.Bind(localEndPoint);//使 Socket 与一个本地终结点相关联。
                listener.Listen(10);//将 Socket 置于侦听状态
               //参数backlog这个参数涉及到一些网络的细节。在进程正理一个一个连接请求的时候,可能还存在其它的连接请求。
               //因为TCP连接是一个过程,所以可能存在一种半连接的状态,有时由于同时尝试连接的用户过多,
               //使得服务器进程无法快速地完成连接请求。如果这个情况出现了,服务器进程希望内核如何处理呢?
               //内核会在自己的进程空间里维护一个队列以跟踪这些完成的连接但服务器进程还没有接手处理或正在进行的连接,
               //这样的一个队列内核不可能让其任意大,所以必须有一个大小的上限。这个backlog告诉内核使用这个数值作为上限。
               //毫无疑问,服务器进程不能随便指定一个数值,内核有一个许可的范围。这个范围是实现相关的。
               //很难有某种统一,一般这个值会小30以内。
    
                // Start listening for connections.
                while (true) {
                    Console.WriteLine("Waiting for a connection...");
                    // Program is suspended while waiting for an incoming connection.
                    Socket handler = listener.Accept();
                    data = null;
    
                    // An incoming connection needs to be processed.
                    while (true) {
                        bytes = new byte[1024];
                        int bytesRec = handler.Receive(bytes);
                        data += Encoding.ASCII.GetString(bytes,0,bytesRec);
                        if (data.IndexOf("<EOF>") > -1) {
                            break;
                        }
                    }
    
                    // Show the data on the console.
                    Console.WriteLine( "Text received : {0}", data);
    
                    // Echo the data back to the client.
                    byte[] msg = Encoding.ASCII.GetBytes(data);
    
                    handler.Send(msg);
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
                
            } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
    
            Console.WriteLine("
    Press ENTER to continue...");
            Console.Read();
            
        }
    
        public static int Main(String[] args) {
            StartListening();
            return 0;
        }
    }
    

     http://msdn.microsoft.com/zh-cn/library/w89fhyex(v=vs.110).aspx

    异步见链接

  • 相关阅读:
    分享诗集中国原创诗歌创作分享中心,欢迎博客园喜欢诗词的加入【诗词在线】
    转让上海水族馆票【吐血转让】08年10月有效【100¥】
    winform 里Control.Margin 属性到底是干嘛的?
    亚交联盟注册指南
    sqlserver 替换回车换行
    如何配置 imail 中域名的MX记录
    张良、萧何与韩信:汉初三杰悲情录[转]
    FBD内存全局缓冲内存 比dd2 ecc还要好啊。服务器内存和普通PC内存的区别[转载]
    脆弱的ASP.NET AJAX
    无法连接到服务器。 帐户: 'mail.bb.cn', 服务器: '*******', 协议: SMTP, 端口: 25, 安全(SSL): 否, 套接字错误: 10061, 错误号: 0x800CCC0E
  • 原文地址:https://www.cnblogs.com/little-white/p/3467173.html
Copyright © 2020-2023  润新知