2023-05-27测试 ,直接用百度文心一言搜索的,结果出来的代码能运行得通,不错不错
服务器端:
using System.Net; using System.Net.Sockets; using System.Text; namespace tcpipdemo_server; class Program { static void Main(string[] args) { // 创建 TCP 服务端实例 TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8208); try { // 开始监听连接请求 listener.Start(); Console.WriteLine("服务端已启动,等待客户端连接..."); // 循环处理客户端连接请求和数据 while (true) { // 接受客户端连接请求 TcpClient client = listener.AcceptTcpClient(); Console.WriteLine("已连接来自 {0}:{1}", client.Client.RemoteEndPoint, client.Client); // 获取网络流并获取数据 NetworkStream stream = client.GetStream(); byte[] data = new byte[1024]; int length = stream.Read(data, 0, data.Length); string message = Encoding.UTF8.GetString(data, 0, length); Console.WriteLine("收到数据:{0}", message); // 处理数据并发送响应数据到客户端 Thread thread = new Thread(() => { // 创建新的网络流并写入响应数据到客户端 using (NetworkStream stream = client.GetStream()) { string response = "Hello, Client!"; byte[] data = Encoding.UTF8.GetBytes(response); stream.Write(data, 0, data.Length); Console.WriteLine("已发送响应数据:{0}", response); } }); thread.Start(); } } catch (Exception ex) { Console.WriteLine("发生异常:{0}", ex); } finally { // 停止监听连接请求并关闭连接 listener.Stop(); } } }
客户端:
using System.Net; using System.Net.Sockets; using System.Text; namespace tcpipdemo; public class Program { static void Main(string[] args) { // 创建 TCP 客户端实例 TcpClient client = new TcpClient(); try { // 连接到服务端 client.Connect("127.0.0.1", 8208); Console.WriteLine("连接已建立"); // 获取网络流 NetworkStream stream = client.GetStream(); // 发送数据到服务端 string message = "Hello, Server!"; byte[] data = Encoding.UTF8.GetBytes(message); stream.Write(data, 0, data.Length); Console.WriteLine("已发送数据:{0}", message); // 从服务端接收数据 data = new byte[1024]; int length = stream.Read(data, 0, data.Length); message = Encoding.UTF8.GetString(data, 0, length); Console.WriteLine("已接收数据:{0}", message); } catch (Exception ex) { Console.WriteLine("发生异常:{0}", ex); } finally { // 关闭连接 client.Close(); } } }
测试结果:客户端发消息到服务器端,服务器端返回消息
标签:Console,示例,client,WriteLine,net7,using,客户端,data,tcpip From: https://www.cnblogs.com/niunan/p/17436606.html