feat(新增): 🚀 使用服务端接受消息,客户端使用debug方式发送消息
This commit is contained in:
parent
d0fecee98d
commit
7a7030a0e4
|
@ -1,32 +1,39 @@
|
|||
package cn.bunny.demo1;
|
||||
package cn.bunny;
|
||||
|
||||
|
||||
import io.netty.bootstrap.Bootstrap;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.socket.nio.NioSocketChannel;
|
||||
import io.netty.handler.codec.string.StringEncoder;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.util.Date;
|
||||
|
||||
public class TestDemoClient {
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
// 启动类
|
||||
new Bootstrap()
|
||||
Channel channel = new Bootstrap()
|
||||
// 添加EventLoop
|
||||
.group(new NioEventLoopGroup())
|
||||
// 选择客户端 Channelt
|
||||
// 设置客户端Channel类型
|
||||
.channel(NioSocketChannel.class)
|
||||
// 选择客户端 Channel
|
||||
.handler(new ChannelInitializer<NioSocketChannel>() {
|
||||
@Override// 在连接建立后调用
|
||||
protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
|
||||
nioSocketChannel.pipeline().addLast(new StringEncoder());
|
||||
}
|
||||
})
|
||||
.connect("localhost", 8080)
|
||||
.connect(new InetSocketAddress("localhost", 8080))
|
||||
.sync()
|
||||
.channel()
|
||||
// 向服务器发送数据
|
||||
.writeAndFlush("你好啊啊啊");
|
||||
.channel();
|
||||
|
||||
System.out.println(channel);// 使用debug方式发送消息...
|
||||
System.out.println();
|
||||
// // 向服务器发送数据
|
||||
// .writeAndFlush("你好啊啊啊");
|
||||
}
|
||||
|
||||
private static void m1() throws InterruptedException {
|
|
@ -0,0 +1,34 @@
|
|||
package cn.bunny.demo3;
|
||||
|
||||
import io.netty.bootstrap.ServerBootstrap;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||
import io.netty.channel.socket.nio.NioSocketChannel;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
@Slf4j
|
||||
public class EventLoopServerTest {
|
||||
public static void main(String[] args) {
|
||||
new ServerBootstrap()
|
||||
.group(new NioEventLoopGroup())
|
||||
.channel(NioServerSocketChannel.class)
|
||||
.childHandler(new ChannelInitializer<NioSocketChannel>() {
|
||||
@Override
|
||||
protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
|
||||
nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
|
||||
@Override
|
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
|
||||
ByteBuf buf = (ByteBuf) msg;
|
||||
log.debug(buf.toString(Charset.defaultCharset()));
|
||||
}
|
||||
});
|
||||
}
|
||||
}).bind(8080);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue