directory

Importing jar packages:

Server start code:

Server configuration information:

Server initialization information:

Server message handling:

client start code:

Client link initialization:

Client message processing:

Server log:

client log:

Here are some personal writing tips for game development and instant messaging

server

client 


Importing jar packages:

Ty < dependency > < groupId > io.net < / groupId > < artifactId > netty -all < / artifactId > < version > 4.1.32. The Final < / version > </dependency>Copy the code

 

Server start code:

package com.supermap.websocket.server; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import java.net.InetSocketAddress; @Component public class NettyServer { // logger private static final Logger logger = Logger.getLogger(NettyServer.class); public void start(InetSocketAddress address) { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap().group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class).localAddress(address) .childHandler(new ServerChannelInitializer()).option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture Future = bootstrap.bind(address).sync(); logger.info("Server start listen at " + address.getPort()); future.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); }}}Copy the code

Server configuration information:

package com.supermap.websocket.server; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.net.InetSocketAddress; @SpringBootApplication public class AppApplication implements CommandLineRunner { @Value("${netty.port}") private int port; @Value("${netty.url}") private String url; @Autowired private NettyServer server; public static void main(String[] args) { SpringApplication.run(AppApplication.class, args); } @Override public void run(String... args) throws Exception { InetSocketAddress address = new InetSocketAddress(url, port); System.out.println("run .... . " + url); server.start(address); }}Copy the code

Server initialization information:

package com.supermap.websocket.server; import io.netty.channel.ChannelInitializer; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.util.CharsetUtil; public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel channel) throws Exception { channel.pipeline().addLast("decoder", new StringDecoder(CharsetUtil.UTF_8)); channel.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8)); channel.pipeline().addLast(new ServerHandler()); }}Copy the code

Server message handling:

package com.supermap.websocket.server; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class ServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) { System.out.println("channelActive----->"); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("server channelRead......" ); System.out.println(ctx.channel().remoteAddress() + "----->Server :" + msg.toString()); If (msg.toString().equals("001")) {// Return the client information to CTX ctx.write("server001"); ctx.flush(); Else {// Write the client information directly back to CTX ctx.writeAndFlush("999"); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); }}Copy the code

 

client start code:

package com.supermap.websocket.client; import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; Public class ClientWebSocket {static final String HOST = system.getProperty (" HOST ", "127.0.0.1"); static final int PORT = Integer.parseInt(System.getProperty("port", "7000")); static final int SIZE = Integer.parseInt(System.getProperty("size", "256")); public static void main(String[] args) throws Exception { sendMessage(); } public static void sendMessage() throws InterruptedException { // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("decoder", new StringDecoder()); p.addLast("encoder", new StringEncoder()); p.addLast(new ClientHandler()); }}); ChannelFuture future = b.connect(HOST, PORT).sync(); future.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); }}}Copy the code

Client link initialization:

package com.supermap.websocket.client; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.util.CharsetUtil; public class ClientChannelInitializer extends ChannelInitializer<SocketChannel> { protected void initChannel(SocketChannel channel) throws Exception { ChannelPipeline p = channel.pipeline(); p.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8)); p.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8)); p.addLast(new ClientHandler()); }}Copy the code

Client message processing:

package com.supermap.websocket.client; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.CharsetUtil; public class ClientHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) { System.out.println("ClientHandler Active"); ctx.writeAndFlush(Unpooled.copiedBuffer("001", CharsetUtil.UTF_8)); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { System.out.println("ClientHandler read Message:" + msg); If (msg.toString().equals("server001")) {writeAndFlush(unpooled.copiedBuffer ("Netty rocks! , charsetutil.utf_8)); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); }}Copy the code

 

Server log:

run .... . 127.0.0.1 2019-05-05 18:25:19. 927 INFO com.supermap.websocket.server.Net tyServer - Server start listen at 7000 channelActive-----> server channelRead...... / 127.0.0.1:11931 -- -- -- -- - > Server: 001 Server channelRead... / 127.0.0.1:11931 -- -- -- -- - > Server: Netty rocks! Very bernaysCopy the code

 

client log:

ClientHandler read Message:server001
ClientHandler read Message:999
Copy the code

 

ok

 

Here are some personal writing tips for game development and instant messaging

server

public void channelRead(ChannelHandlerContext ctx, Object MSG) throws Exception {if(msg.toString().equals("001")) {// Stop ctx.writeAndFlush("over"); }else{// Instant messaging implementation to read the cache service layer to see if there is a service associated with the user, if there is a service through the user // game style, can write a private variable and a public variable, // system.out. print("input send client info: "); // String read = new Scanner(System.in).nextLine(); // if (read.equals("quit")) {// Get different information to do different tasks // // end here //}else {// ctx.writeAndFlush(unpooled.copiedBuffer (read, CharsetUtil.UTF_8)); // } ctx.writeAndFlush("ready"); } system.out.println (ctx.channel().remoteAddress() + "----->Server :" + msg.tostring ()); }Copy the code

client 

public void channelRead(ChannelHandlerContext ctx, Object msg) { System.out.println("server Message:" + msg); If (msg.tostring ().equals("ready")) {if (msg.tostring ().equals("ready")) { Print (" Input send client info: "); system.out. print("input send client info: "); String read = new Scanner(System.in).nextLine(); If (read. Equals ("quit")) {// end here}else {ctx.writeAndFlush(Unpooled. CopiedBuffer (read, charsetutil.utf_8)); } } else if (msg.toString().equals("over")) { } }Copy the code

 

If you have better suggestions, give them more

ok

The article continues to be updated