- 定义proto结构
im.proto
syntax ="proto3";
//optimize_for 加快解析的速度
option optimize_for = SPEED;
option java_package = "sample.cluster.nettyim";
option java_outer_classname="MessageData";
option java_multiple_files = true;
// 客户端发送过来的消息实体
message RequestUser{
optional string user_name = 1;
optional int32 age = 2;
optional string password = 3;
}
// 返回给客户端的消息实体
message ResponseUser{
optional string user_name = 1;
optional int32 age = 2;
optional string password = 3;
}
生成java代码,进入到im.proto所在文件夹
protoc --java_out=./ ./im.proto
Server.java
package sample.cluster.nettyim;
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;
//websocket长连接示例
public class Server {
public static void main(String[] args) throws Exception{
// 主线程组
EventLoopGroup bossGroup = new NioEventLoopGroup();
// 从线程组
EventLoopGroup wokerGroup = new NioEventLoopGroup();
try{
ServerBootstrap serverBootstrap = n