1. 服务端代码
// 1. 新建一个Socket 服务器端 连接对象
// 参数 寻址范围,数据类型,协议格式
Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
byte[] ip = { 192, 168, 199, 117 };
IPAddress address = new IPAddress(ip);
IPEndPoint point = new IPEndPoint(address, 8090);
tcpServer.Bind(point); // 2. 绑定Ip和端口号
tcpServer.Listen(100); // 3. 设置监听连接的最大请求数
Socket newSocket = tcpServer.Accept(); // 4. 等待客户端的连接,会阻塞当前线程,直到接收到客户端的连接
string sendMessage = "Hello Welcome Connect";
newSocket.Send(Encoding.UTF8.GetBytes(sendMessage)); // 5.向客户端发送一条消息
byte[] data = new byte[1024];
int length = newSocket.Receive(data);
Console.WriteLine("接收到客户端的数据"+Encoding.UTF8.GetString(data, 0, length));
Console.ReadKey();
2. 客户端代码
//1. 建立客户端连接对象
// 参数 寻址范围,数据类型,协议格式
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 2. 建立一个连接,请求连接到服务器
clientSocket.Connect(new IPEndPoint(new IPAddress(new byte[] { 192, 168, 199, 117 }), 8090));
// 建立一个用来接受数据的容器
byte[] data = new byte[1024];
// 3. 接受服务端发送的数据
int length = clientSocket.Receive(data); // 该数组用来接受数组,接受服务端传递的数据 , 返回值,用来表示本次接收到的数据长度
// 4. 将服务器端发送过来的数据转换成字符串
string reciveMessage = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine(reciveMessage);
string message = Console.ReadLine();
clientSocket.Send(Encoding.UTF8.GetBytes(message));
Console.ReadKey();
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。