C#:TcpClient(客户端) and TcpServer(服务端)

服务端:

 

 

客户端:

 

附客户端WPF代码:

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
当然可以!下面是一个简单的示例代码,展示了如何使用C#TcpClient类实现服务端客户端之间的通信。 服务端代码: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; class Server { static void Main() { TcpListener server = null; try { // 设置服务端IP地址和端口号 IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); int port = 8888; // 创建TcpListener对象 server = new TcpListener(ipAddress, port); // 开始监听客户端连接请求 server.Start(); Console.WriteLine("服务端已启动,等待客户端连接..."); // 接受客户端连接请求 TcpClient client = server.AcceptTcpClient(); Console.WriteLine("客户端已连接!"); // 获取网络流 NetworkStream stream = client.GetStream(); // 接收客户端消息 byte[] buffer = new byte[1024]; int bytesRead = stream.Read(buffer, 0, buffer.Length); string message = Encoding.ASCII.GetString(buffer, 0, bytesRead); Console.WriteLine("收到客户端消息: {0}", message); // 向客户端发送响应 byte[] response = Encoding.ASCII.GetBytes("服务端已收到消息!"); stream.Write(response, 0, response.Length); Console.WriteLine("已向客户端发送响应!"); // 关闭连接 client.Close(); } catch (Exception e) { Console.WriteLine("发生异常: {0}", e); } finally { // 停止监听 server.Stop(); } Console.WriteLine("按任意键退出..."); Console.ReadKey(); } } ``` 客户端代码: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; class Client { static void Main() { try { // 设置服务端IP地址和端口号 IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); int port = 8888; // 创建TcpClient对象并连接到服务端 TcpClient client = new TcpClient(); client.Connect(ipAddress, port); Console.WriteLine("已连接到服务端!"); // 获取网络流 NetworkStream stream = client.GetStream(); // 向服务端发送消息 string message = "Hello, Server!"; byte[] data = Encoding.ASCII.GetBytes(message); stream.Write(data, 0, data.Length); Console.WriteLine("已向服务端发送消息: {0}", message); // 接收服务端响应 data = new byte[1024]; int bytesRead = stream.Read(data, 0, data.Length); string response = Encoding.ASCII.GetString(data, 0, bytesRead); Console.WriteLine("收到服务端响应: {0}", response); // 关闭连接 client.Close(); } catch (Exception e) { Console.WriteLine("发生异常: {0}", e); } Console.WriteLine("按任意键退出..."); Console.ReadKey(); } } ``` 使用以上代码,你可以在本地运行一个简单的服务端客户端,实现它们之间的通信。记得将IP地址和端口号设置为你的实际需求。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值