[C#]Socket简单TCP客户端-服务端
服务端
using System; using System.Net; using System.Net.Sockets; using System.Text; namespace TcpServer { internal class Program { static void Main(string[] args) { Socket theSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress theIPAddress = new IPAddress(new byte[] { 192,168,2,133 }); IPEndPoint theIPEndPoint = new IPEndPoint(theIPAddress, 7788); theSocket.Bind(theIPEndPoint); theSocket.Listen(100); Console.WriteLine("服务端已开启"); Socket theSocketServer = theSocket.Accept(); Console.WriteLine("客户端请求连接"); byte[] byt_aData = new byte[1024]; int intLength = theSocketServer.Receive(byt_aData); string strMessage = Encoding.UTF8.GetString(byt_aData, 0, intLength); Console.WriteLine("接收到了客户端的消息:" + strMessage); theSocketServer.Send(Encoding.UTF8.GetBytes("我是服务端")); theSocketServer.Close(); theSocket.Close(); } } }
客户端
using System.Net; using System.Net.Sockets; using System.Text; namespace TcpClient { class Program { static void Main(string[] args) { Socket theSocket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress theIPAddress = new(new byte[] { 192, 168, 2, 133 }); IPEndPoint theIPEndPoint = new(theIPAddress, 7788); theSocket.Connect(theIPEndPoint); Console.WriteLine("已连接服务端"); string strMessage = "我是客户端"; theSocket.Send(Encoding.UTF8.GetBytes(strMessage)); byte[] byt_aData = new byte[1024]; int intLength = theSocket.Receive(byt_aData); Console.WriteLine("收到服务端的消息:" + Encoding.UTF8.GetString(byt_aData, 0, intLength)); theSocket.Close(); } } }
演示(需要先开启服务端再开启客户端)