日期:2014-05-18  浏览次数:20913 次

C# socket 服务端实例

        IPAddress ipAddress;
        IPEndPoint remoteEP ;
        // Create a TCP/IP  socket
        Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        private Boolean sendUid(string uid)
        {
            byte[] bytes = new byte[10];
            try
            {
                sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                ipAddress = IPAddress.Parse(FaceToolIP.Text.Trim());
                remoteEP = new IPEndPoint(ipAddress, Convert.ToInt32(FaceToolPort.Text));
                // Connect the socket to the remote endpoint. Catch any errors.
                sender.Connect(remoteEP);
                sender.Send(Encoding.Default.GetBytes(uid));
                int bytesRec = sender.Receive(bytes);
                string result = Encoding.ASCII.GetString(bytes, 0, bytesRec);
                lInfo.Items.Add(result);
                if(!result.Equals("ok"))
                {
                    return false;
                }
                
                sender.Close();
                

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return false;
            }
            return true;
        }
?