服务器端 using System.Net.Sockets; using System.Net;
Socket tcp=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); IPAdress ipAddress = new IPAddress(new byte[] { 192.168.1.155 }); IpEndPoint ipEndPoint =new IPEndPoint(ipAddress,7788); tcpServer.Bind(ipEndPoint ); tcpServer.listen(100);//最大连接数量 Socket client = tcpServer.Accept(); //开始监听,并将监听到的客户端返回,此时程序暂停(线程),直到有返回值
byte[]data = new byte[1024]; int length= client.Receive(data); String message = Encoding.UTF8.GetString(data,0,length); Console.Write(“接收到了消息”+message); client.Send(Encoding.UTF8.GetBytes(“发送给客户端的消息”));
client.Close(); tcpServer.Close();
客户端 using System.Net.Sockets; using System.Net; using System.Text;
Socket tcpClient=new Socket(AddressFamily.InterNetwork,Socket.Stream,ProtocolType.Tcp); IPAdress ipAddress = new IPAddress(new byte[] { 192.168.1.155 }); IpEndPoint ipEndPoint =new IPEndPoint(ipAddress,7788); tcpClient.Connect(ipEndPoint);//此处区别于服务器,没有返回值
//发送消息 string message=“我来了哦” TcpClient.Send( Encoding.UTF8.GetBytes(message));// 转化为2进制,UTF8支持中文,很常用 byte[] data=new byte[1024]; int length=tcpClient.Receive(data,0,length); String receiveMes=Encoding.UTF8.GetString(data,0,length);
tcpClient.Close();
|