在C#中可以使用DotNetty來實現TCP通信,以下是一個簡單的示例代碼:
using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Common.Concurrency;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using System;
using System.Net;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
var group = new MultithreadEventLoopGroup();
var bootstrap = new ServerBootstrap();
bootstrap
.Group(group)
.Channel<TcpServerSocketChannel>()
.Option(ChannelOption.SoBacklog, 100)
.Handler(new LoggingHandler(LogLevel.INFO))
.ChildHandler(new ActionChannelInitializer<ISocketChannel>(channel =>
{
IChannelPipeline pipeline = channel.Pipeline;
pipeline.AddLast(new LengthFieldBasedFrameDecoder(ByteOrder.BigEndian, int.MaxValue, 0, 4, 0, 4, true));
pipeline.AddLast(new LengthFieldPrepender(ByteOrder.BigEndian, 4, 0, false));
pipeline.AddLast(new StringEncoder(Encoding.UTF8));
pipeline.AddLast(new StringDecoder(Encoding.UTF8));
pipeline.AddLast(new SimpleServerHandler());
}));
IChannel boundChannel = await bootstrap.BindAsync(IPAddress.Parse("127.0.0.1"), 8888);
Console.ReadLine();
await boundChannel.CloseAsync();
await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
}
}
public class SimpleServerHandler : SimpleChannelInboundHandler<string>
{
protected override void ChannelRead0(IChannelHandlerContext ctx, string msg)
{
Console.WriteLine($"Received from client: {msg}");
// Echo back to client
ctx.WriteAndFlushAsync(msg);
}
public override void ExceptionCaught(IChannelHandlerContext ctx, Exception cause)
{
Console.WriteLine($"Exception: {cause}");
ctx.CloseAsync();
}
}
以上代碼是一個簡單的TCP服務器示例,它監聽本地IP地址127.0.0.1的8888端口,并使用DotNetty來處理TCP通信。在SimpleServerHandler
類中,實現了處理接收到的消息和異常的方法。可以根據實際需求修改代碼來實現自定義的TCP通信邏輯。