Socket 双向通讯, usb socket 通讯

client

  ///

    
        ///  发送消息到PC机的Tcp端口,默认端口为:8888 
        /// 
 
        ///  要发送的消息   
        ///  远程服务器端的TCP端口 
        ///  运行时发生的错误的提示信息 
         public static void SendInfo(string info, int port) 
        {    
            
             try     
             {      
                 IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
                 IPEndPoint localIpEndPoint = new IPEndPoint(host.AddressList[0], 0);  
                 IPHostEntry rhost = Dns.GetHostEntry("ppp_peer");
                 IPAddress rhost_ipaddr = rhost.AddressList[0];  
                 IPEndPoint RemoteIpEndPoint = new IPEndPoint(rhost_ipaddr, port);//远程服务器端
                 Byte[] sendBytes = Encoding.ASCII.GetBytes(info);
                 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);          
                          
                     socket.Bind(localIpEndPoint);
                     socket.Connect(RemoteIpEndPoint);
                     socket.Send(sendBytes, SocketFlags.None); 
                     //  
               byte[] data=new byte[1024];
               int recv=socket.Receive(data);
               string stringdata=Encoding.ASCII.GetString(data,0,recv);
               MessageBox.Show(stringdata);
 
                    
             }        
             catch (Exception ex)  
             {            
               
                   
             }     
         }

 

server

 void cs()
        { 
            int recv;//用于表示客户端发送的信息长度
            byte[] data = new byte[1024];//用于缓存客户端所发送的信息,通过socket传递的信息必须为字节数组
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9999);//本机预使用的IP和端口
            Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            newsock.Bind(ipep);//绑定
            newsock.Listen(10);//监听
           
            Socket client = newsock.Accept();//当有可用的客户端连接尝试时执行,并返回一个新的socket,用于与客户端之间的通信
            IPEndPoint clientip = (IPEndPoint)client.RemoteEndPoint;
            MessageBox.Show("connect with client:" + clientip.Address + " at port:" + clientip.Port);
            string welcome = "welcome here!";
            data = Encoding.ASCII.GetBytes(welcome);
            client.Send(data, data.Length, SocketFlags.None);//发送信息
            while (true)
            {//用死循环来不断的从客户端获取信息
                data = new byte[1024];
                recv = client.Receive(data);
                Console.WriteLine("recv=" + recv);
                if (recv == 0)//当信息长度为0,说明客户端连接断开
                    break;
                MessageBox.Show(Encoding.ASCII.GetString(data, 0, recv));
                //client.Send(data, recv, SocketFlags.None);
            }
          
            client.Close();
            newsock.Close();

        }

 

你可能感兴趣的:(socket)