客户端
static void Main(string[] args) { Console.WriteLine("this is a Client!"); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8000)); while (true) { string sendmsg = Console.ReadLine(); client.Send(System.Text.Encoding.Default.GetBytes(sendmsg)); Console.WriteLine(sendmsg + " is send Ok!"); }
服务器
static void Main(string[] args) { Console.WriteLine("this is a Server!"); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); server.Bind(new IPEndPoint(IPAddress.Any, 8000)); server.Listen(50); server.BeginAccept(Callback, server); Console.ReadLine(); } static void Callback(IAsyncResult ar) { Socket server = (Socket)ar.AsyncState; Socket client = server.EndAccept(ar); while (true) { byte[] buffer = new byte[100]; client.Receive(buffer,0,buffer.Length,SocketFlags.None); Console.WriteLine(System.Text.Encoding.Default.GetString(buffer).Trim()); } }