C# Socket

作者: GongZH丶 | 来源:发表于2018-09-14 13:53 被阅读23次

    通过socket往一个服务器发送一条数据;

        public class SocketRequest
        {    
            //传入参数 hostname和port,messages是要发送的字符串
            public static string SendSocketRequest(string address, int port, string messages)
            {
                //IPAddress ip = DoGetHostAddresses("www.....com");
                IPAddress ip = DoGetHostAddresses(address);
                //int port = 8000;
    
                Socket ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint Point = new IPEndPoint(ip, port);
                ClientSocket.Connect(Point);  //与远程主机建立连接
    
                string requestStr = messages; //要发送的数据的字符串
    
                byte[] message = Encoding.UTF8.GetBytes(requestStr);
                ClientSocket.Send(message); //发送数据
    
                byte[] receive = new byte[1024];
                int length = ClientSocket.Receive(receive);  // length 接收字节数组长度
    
                string responseStr = Encoding.UTF8.GetString(receive).Substring(0, length);
    
                ClientSocket.Close();  //关闭连接
    
                return responseStr;
    
            }
    
            public static IPAddress DoGetHostAddresses(string hostname)
            {
                IPAddress[] ips;
                ips = Dns.GetHostAddresses(hostname);
                return ips[0];
            }
        }
    

    相关文章

      网友评论

        本文标题:C# Socket

        本文链接:https://www.haomeiwen.com/subject/kflggftx.html