在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通信逻辑。