server
package com.deppyu.netty.demo.server;
import com.deppyu.netty.demo.server.websocket.WebSocketInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import java.net.InetSocketAddress;
/**
* @author deppyu
* @date 2019-08-05 19:14
*/
public class NettyServer {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
NioEventLoopGroup workGroup = new NioEventLoopGroup();
try{
ServerBootstrap serverBootstrap = new ServerBootstrap().group(bossGroup , workGroup).
channel(NioServerSocketChannel.class).
handler(new LoggingHandler(LogLevel.INFO)).
childHandler(new WebSocketInitializer());
ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(5566)).sync();
channelFuture.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
}
client
package com.deppyu.netty.demo.client;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author deppyu
* @date 2019-08-05 19:14
*/
public class NettyClient {
public static void main(String[] args) throws InterruptedException, IOException {
EventLoopGroup eventGroup = new NioEventLoopGroup();
try{
Bootstrap bootstrap = new Bootstrap().group(eventGroup).
channel(NioSocketChannel.class).
handler(new ClientInitializer());
ChannelFuture channelFuture = bootstrap.connect("localhost",5566).sync();
Channel channel = channelFuture.channel();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for(;;){
channel.writeAndFlush(br.readLine() + "\r\n");
}
// channel.closeFuture().sync();
}finally {
eventGroup.shutdownGracefully();
}
}
}