使用Socket編寫服務端和客戶端

使用Socket編寫服務端和客戶端 服務端 const int PORT = 6602; Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ip = IPAddress.Any; IPEndPoint ep = new IPEndPoint(ip, PORT); listener.Bind(ep); listener.Listen(10); while (true) { Console.WriteLine("Waiting for connection on port 6602"); Socket socket = listener.Accept(); string rec = string.Empty; while (true)//接收字符串 { byte[] recBytes = new byte[1024]; int numBytes = socket.Receive(recBytes); Console.WriteLine("Receiving..."); rec += Encoding.UTF8.GetString(recBytes, 0, numBytes); if (rec.IndexOf("[END]") != -1) break; } Console.WriteLine("Received string: {0}", rec); //rec是收到的字符串 socket.Shutdown(SocketShutdown.Both); socket.Close(); }

客戶端 已經寫成了一個函數方便重複使用 /// /// 經過socket發送信息 /// /// 要發送的字符串 /// IP地址 /// 端口 private static void socketSendMessage(string sendMsg, string stringIP, int port) { byte[] recBytes = new byte[1024]; IPHostEntry iphost = Dns.GetHostEntry(stringIP); IPAddress[] ipaddresses = iphost.AddressList; IPAddress ipaddress = ipaddresses[0]; foreach (IPAddress i in ipaddresses) { if (i.AddressFamily == AddressFamily.InterNetwork) { ipaddress = i; break; } } IPEndPoint ipendpoint = new IPEndPoint(ipaddress, port); Console.WriteLine("Starting..."); Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, Type.Tcp); sender.Connect(ipendpoint); Console.WriteLine("Connected to {0}", sender.RemoteEndPoint); Console.WriteLine("Msg is {0}", sendMsg); byte[] sendMsgByte = Encoding.UTF8.GetBytes(sendMsg + "[END]"); sender.Send(sendMsgByte); sender.Shutdown(SocketShutdown.Both); sender.Close(); Console.ReadKey(); }
相關文章
相關標籤/搜索