这是服务器端代码
static void Main(string[] args) { try { int port = 2000; string host = "127.0.0.1"; IPAddress ip = IPAddress.Parse(host); IPEndPoint ipe = new IPEndPoint(ip, port); Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket类 s.Bind(ipe);//绑定2000端口 s.Listen(0);//开始监听 Console.WriteLine("等待连接"); Socket temp = s.Accept();//为新建连接创建新的Socket。 Console.WriteLine("获取新连接"); string recvStr = ""; byte[] recvBytes = new byte[1024]; int bytes; bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息 recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes); Console.WriteLine("服务器接受信息:{0}", recvStr);//把客户端传来的信息显示出来 string sendStr = "服务器发送信息成功!"; byte[] bs = Encoding.UTF8.GetBytes(sendStr); temp.Send(bs, bs.Length, 0);//返回客户端成功信息 temp.Close(); s.Close(); } catch (ArgumentNullException e) { Console.WriteLine("参数异常: {0}", e); } catch (SocketException e) { Console.WriteLine("套接字异常: {0}", e); } Console.WriteLine("按回车键退出"); Console.ReadLine(); }
这是客户端代码,两台机器是局域网
try { int port = 2000; string host = "192.168.3.141"; IPAddress ip = IPAddress.Parse(host); IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例 Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket result.Text = "正在连接......"; c.Connect(ipe);//连接到服务器 string sendStr = "这是测试信息!"; byte[] bs = Encoding.UTF8.GetBytes(sendStr); result.Text = "发送测试消息"; c.Send(bs, bs.Length, 0);//发送测试信息 string recvStr = ""; byte[] recvBytes = new byte[1024]; int bytes; bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息 recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes); //Console.WriteLine("Client Get Message:{0}", recvStr);//显示服务器返回信息 result.Text = "客户端接受信息:" + recvStr; c.Close(); } catch (ArgumentNullException ae) { Console.WriteLine("参数异常: {0}", ae); } catch (SocketException se) { Console.WriteLine("套接字异常: {0}", se); } }
服务器绑定的IP要改为192.168.3.141,或者使用IPAddress.Any。
赞,解决了