一服务器
using System;
using System.Text;
using System.Threading.Tasks;
using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Common.Concurrency;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
namespace Nettyfwq
{
public class TcpServer
{
public async Task Start()
{
IEventLoopGroup bossGroup = new MultithreadEventLoopGroup(1);
IEventLoopGroup workerGroup = new MultithreadEventLoopGroup();
try
{
ServerBootstrap bootstrap = new ServerBootstrap()
.Group(bossGroup, workerGroup)
.Channel<TcpServerSocketChannel>()
.Option(ChannelOption.SoBacklog, 100)
.ChildHandler(new ActionChannelInitializer<ISocketChannel>(channel =>
{
IChannelPipeline pipeline = channel.Pipeline;
pipeline.AddLast(new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4));
pipeline.AddLast(new StringDecoder(Encoding.UTF8));
pipeline.AddLast(new LengthFieldPrepender(4));
pipeline.AddLast(new StringEncoder(Encoding.UTF8));
pipeline.AddLast(new TcpServerHandler());
}));
IChannel boundChannel = await bootstrap.BindAsync(8888);
Console.WriteLine("TCP server started on port 8888. Press any key to exit.");
Console.ReadKey();
await boundChannel.CloseAsync();
}
finally
{
await Task.WhenAll(
bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)),
workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1))
);
}
}
}
public class TcpServerHandler : SimpleChannelInboundHandler<string>
{
protected override void ChannelRead0(IChannelHandlerContext context, string message)
{
Console.WriteLine($"Received data: {message}");
context.Channel.WriteAndFlushAsync("我是服务器");
}
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
{
Console.WriteLine($"Exception: {exception}");
context.CloseAsync();
}
public override void ChannelActive(IChannelHandlerContext context)
{
string clientName = context.Channel.RemoteAddress.ToString();
Console.WriteLine("连接到一台客户端:" + clientName);
base.ChannelActive(context);
Console.WriteLine("连接到一台客户端:" + clientName);
}
}
public class Program
{
public static async Task Main(string[] args)
{
TcpServer server = new TcpServer();
await server.Start();
}
}
}
二客户端
using System;
using System.Text;
using System.Threading.Tasks;
using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Common.Concurrency;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
namespace Nuttykhd
{
public class DotNettyClient
{
private MultithreadEventLoopGroup group;
private Bootstrap bootstrap;
private IChannel channel;
public async Task StartAsync()
{
group = new MultithreadEventLoopGroup();
try
{
bootstrap = new Bootstrap()
.Group(group)
.Channel<TcpSocketChannel>()
.Option(ChannelOption.TcpNodelay, true)
.Handler(new ActionChannelInitializer<ISocketChannel>(channel =>
{
IChannelPipeline pipeline = channel.Pipeline;
pipeline.AddLast(new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4));
pipeline.AddLast(new StringDecoder(Encoding.UTF8));
pipeline.AddLast(new LengthFieldPrepender(4));
pipeline.AddLast(new StringEncoder(Encoding.UTF8));
pipeline.AddLast(new DotNettyClientHandler());
}));
channel = await bootstrap.ConnectAsync("127.0.0.1", 8888);
string clientName = "小王";
byte[] nameBytes = Encoding.UTF8.GetBytes(clientName);
await channel.WriteAndFlushAsync(Unpooled.WrappedBuffer(nameBytes));
Console.WriteLine("Connected to server.");
SendMessage("我是客户端");
await Task.Delay(5000);
SendMessage("我发 发阿飞");
}
finally
{
await group.ShutdownGracefullyAsync();
}
}
public void SendMessage(string message)
{
if (channel != null && channel.Open)
{
channel.WriteAndFlushAsync(message);
Console.WriteLine("Sent message to server: " + message);
}
}
}
public class DotNettyClientHandler : SimpleChannelInboundHandler<string>
{
protected override void ChannelRead0(IChannelHandlerContext context, string message)
{
Console.WriteLine("Received message from server: " + message);
}
}
public class Program
{
public static async Task Main()
{
DotNettyClient client = new DotNettyClient();
await client.StartAsync();
}
}
}