C#中编写TCP客户端和服务端

在C#中编写TCP客户端和服务端涉及到System.Net.Sockets命名空间中的TcpListener和TcpClient类。下面分别给出一个简单的TCP服务端和客户端的示例代码。

using System;

using System.Net;

using System.Net.Sockets;

using System.Text;

public class TcpServer

{

public static void StartServer()

{

// 监听的IP和端口

IPAddress ipAddress = IPAddress.Parse("127.0.0.1");

int port = 8888;

// 创建TcpListener实例

TcpListener listener = new TcpListener(ipAddress, port);

Console.WriteLine($"服务器启动,等待连接: {ipAddress}:{port}");

// 开始监听

listener.Start();

try

{

while (true)

{

// 等待客户端连接

TcpClient client = listener.AcceptTcpClient();

Console.WriteLine("客户端已连接");

// 获取网络流,用于读取客户端发送的数据

NetworkStream stream = client.GetStream();

// 读取数据

byte[] buffer = new byte[1024];

int read = stream.Read(buffer, 0, buffer.Length);

string dataReceived = Encoding.ASCII.GetString(buffer, 0, read);

Console.WriteLine($"接收到的消息: {dataReceived}");

// 发送响应

string response = "你好,客户端!";

byte[] sendData = Encoding.ASCII.GetBytes(response);

stream.Write(sendData, 0, sendData.Length);

// 关闭客户端连接

client.Close();

}

}

catch (Exception ex)

{

Console.WriteLine(ex.ToString());

}

finally

{

// 停止监听

listener.Stop();

}

}

public static void Main(string[] args)

{

StartServer();

}

}

这些示例假设在同一台机器上运行服务端和客户端,因此使用了localhost(即127.0.0.1)作为IP地址。在实际应用中,服务端IP应为实际服务器的IP地址。

在实际部署时,确保防火墙配置允许相应的端口通信。

这些代码仅提供了基本功能,生产环境中可能需要更复杂的错误处理和性能优化。

相关推荐
Scout-leaf1 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530141 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools2 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的3 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21883 天前
.NET 本地Db数据库-技术方案选型
windows·c#
郑州光合科技余经理3 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
lindexi3 天前
dotnet DirectX 通过可等待交换链降低输入渲染延迟
c#·directx·d2d·direct2d·vortice
feifeigo1233 天前
matlab画图工具
开发语言·matlab
dustcell.3 天前
haproxy七层代理
java·开发语言·前端
norlan_jame3 天前
C-PHY与D-PHY差异
c语言·开发语言