本文整合网上资料 给出了一个完整版本
对于高负载、高并发的网络应用,自己开发nio服务端,难度比较大、稳定性不能保证。于是选择nio框架netty+protobuf。netty对于消息编码和解码、半包读写问题支持很好;protobuf支持多语言,编码后消息小利于存储和传输。
版本:java7 netty5 protobuf-java-2.5.0
maven 依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0.0.Alpha2</version>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>2.5.0</version>
</dependency>
protobuf 消息定义如下:
Auth.proto
option java_package = "com.bimatrix.revit.nettyProtobuf";
package auth;
message AuthRequest{ // (1)
required string user_id=1;
required string password=2;
}
message AuthResponse{ //(2)
required int32 result_code=1;
required string result_message=2;
}
说明:
(1)请求消息,包括用户ID和密码
(2)应答消息,包括响应码和响应说明
protobuf 文件转java 文件 参考
http://download.csdn.net/detail/zhshchilss/8470577
Auth.java(Auth.proto编译后的java文件)
这个文件很长 在本文最后放出
AuthServer.java AuthServerInitHandler.java
package com.bimatrix.revit.nettyProtobuf;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;
public class AuthService {
private static Logger logger = Logger.getLogger(AuthServerInitHandler.class
.getName());
public void start(int port) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();// (1)
EventLoopGroup workerGroup = new NioEventLoopGroup();// (2)
try {
ServerBootstrap b = new ServerBootstrap();// (3)
b.group(bossGroup, workerGroup); // (4)
b.channel(NioServerSocketChannel.class);
/* b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast(new TcpServerHandler());
}
});*/
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//decoded
ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4));
ch.pipeline().addLast(new ProtobufDecoder(Auth.AuthRequest.getDefaultInstance()));
//encoded
ch.pipeline().addLast(new LengthFieldPrepender(4));
ch.pipeline().addLast(new ProtobufEncoder());
// 注册handler
ch.pipeline().addLast(new AuthServerInitHandler());
}
});
b.option(ChannelOption.SO_BACKLOG, 128);
b.childOption(ChannelOption.SO_KEEPALIVE, true);
//绑定端口 同步等待成功
ChannelFuture f = b.bind(port).sync();
//等待服务端监听端口关闭
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
logger.log(Level.INFO, "AuthServer start...");
new AuthService().start(5555);
}
}
AuthServerInitHandler.java
注意 AuthResponse对象在下面赋值时 字段不能不写(比如某个字段不能漏掉 会报错 且字段不能赋值为null)
package com.bimatrix.revit.nettyProtobuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.util.logging.Level;
import java.util.logging.Logger;
public class AuthServerInitHandler extends ChannelInboundHandlerAdapter{
private Logger logger=Logger.getLogger(AuthServerInitHandler.class.getName());
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
logger.log(Level.INFO, "AuthServerInitHandler channelRead");
Auth.AuthRequest request=(Auth.AuthRequest)msg;
System.out.println("request: userId="+request.getUserId()+", password="+request.getPassword());
Auth.AuthResponse response=Auth.AuthResponse.newBuilder()
.setResultCode(0)
.setResultMessage("success")
.build();
ctx.writeAndFlush(response);
//ctx.close();
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
logger.log(Level.INFO, "AuthServerInitHandler channelReadComplete");
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
logger.log(Level.INFO, "AuthServerInitHandler exceptionCaught");
cause.printStackTrace();
ctx.close();
}
}
AuthClient.java AuthClientInitHandler.java
AuthClient.java
package com.bimatrix.revit.nettyProtobuf;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
public class AuthClient {
public void connect(String host,int port) throws Exception{
EventLoopGroup workerGroup=new NioEventLoopGroup();
try{
Bootstrap b=new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//decoded
ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4));
ch.pipeline().addLast(new ProtobufDecoder(Auth.AuthResponse.getDefaultInstance()));
//encoded
ch.pipeline().addLast(new LengthFieldPrepender(4));
ch.pipeline().addLast(new ProtobufEncoder());
// 注册handler
ch.pipeline().addLast(new AuthClientInitHandler());
}
});
ChannelFuture f=b.connect(host, port).sync();
f.channel().closeFuture().sync();
}finally{
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
new AuthClient().connect("127.0.0.1", 5555);
}
}
AuthClientInitHandler.java
package com.bimatrix.revit.nettyProtobuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class AuthClientInitHandler extends ChannelInboundHandlerAdapter{
private Logger logger=Logger.getLogger(AuthClientInitHandler.class.getName());
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
logger.log(Level.INFO, "AuthClientInitHandler exceptionCaught");
Auth.AuthRequest request=Auth.AuthRequest.newBuilder()
.setUserId("010203")
.setPassword("abcde")
.build();
List<Auth.AuthRequest> sendData = new ArrayList<Auth.AuthRequest>();
Auth.AuthRequest request1=Auth.AuthRequest.newBuilder()
.setUserId("111")
.setPassword("word")
.build();
sendData.add(request1);
sendData.add(request);
for(int i=0;i<100;i++){
if(i%2==0){
ctx.writeAndFlush(request1);
}else{
ctx.writeAndFlush(request);
}
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
logger.log(Level.INFO, "AuthClientInitHandler channelRead");
Auth.AuthResponse response=(Auth.AuthResponse)msg;
System.out.println("response: code="+response.getResultCode()+", message="+response.getResultMessage());
//ctx.close();
}
}
Auth.java(Auth.proto编译后的java文件)
这个文件很长
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Auth.proto
package com.bimatrix.revit.nettyProtobuf;
public final class Auth {
private Auth() {
}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
}
public interface AuthRequestOrBuilder extends com.google.protobuf.MessageOrBuilder {
// required string user_id = 1;
/**
* <code>required string user_id = 1;</code>
*/
boolean hasUserId();
/**
* <code>required string user_id = 1;</code>
*/
java.lang.String getUserId();
/**
* <code>required string user_id = 1;</code>
*/
com.google.protobuf.ByteString getUserIdBytes();
// required string password = 2;
/**
* <code>required string password = 2;</code>
*/
boolean hasPassword();
/**
* <code>required string password = 2;</code>
*/
java.lang.String getPassword();
/**
* <code>required string password = 2;</code>
*/
com.google.protobuf.ByteString getPasswordBytes();
}
/**
* Protobuf type {@code auth.AuthRequest}
*
* <pre>
* (1)
* </pre>
*/
public static final class AuthRequest extends com.google.protobuf.GeneratedMessage implements AuthRequestOrBuilder {
// Use AuthRequest.newBuilder() to construct.
private AuthRequest(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private AuthRequest(boolean noInit) {
this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
private static final AuthRequest defaultInstance;
public static AuthRequest getDefaultInstance() {
return defaultInstance;
}
public AuthRequest getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private AuthRequest(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
bitField0_ |= 0x00000001;
userId_ = input.readBytes();
break;
}
case 18: {
bitField0_ |= 0x00000002;
password_ = input.readBytes();
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.bimatrix.revit.nettyProtobuf.Auth.internal_static_auth_AuthRequest_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() {
return com.bimatrix.revit.nettyProtobuf.Auth.internal_static_auth_AuthRequest_fieldAccessorTable.ensureFieldAccessorsInitialized(
com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest.class, com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest.Builder.class);
}
public static com.google.protobuf.Parser<AuthRequest> PARSER = new com.google.protobuf.AbstractParser<AuthRequest>() {
public AuthRequest parsePartialFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new AuthRequest(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<AuthRequest> getParserForType() {
return PARSER;
}
private int bitField0_;
// required string user_id = 1;
public static final int USER_ID_FIELD_NUMBER = 1;
private java.lang.Object userId_;
/**
* <code>required string user_id = 1;</code>
*/
public boolean hasUserId() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required string user_id = 1;</code>
*/
public java.lang.String getUserId() {
java.lang.Object ref = userId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
userId_ = s;
}
return s;
}
}
/**
* <code>required string user_id = 1;</code>
*/
public com.google.protobuf.ByteString getUserIdBytes() {
java.lang.Object ref = userId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
userId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
// required string password = 2;
public static final int PASSWORD_FIELD_NUMBER = 2;
private java.lang.Object password_;
/**
* <code>required string password = 2;</code>
*/
public boolean hasPassword() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string password = 2;</code>
*/
public java.lang.String getPassword() {
java.lang.Object ref = password_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
password_ = s;
}
return s;
}
}
/**
* <code>required string password = 2;</code>
*/
public com.google.protobuf.ByteString getPasswordBytes() {
java.lang.Object ref = password_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
password_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private void initFields() {
userId_ = "";
password_ = "";
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1)
return isInitialized == 1;
if (!hasUserId()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasPassword()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeBytes(1, getUserIdBytes());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBytes(2, getPasswordBytes());
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1)
return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream.computeBytesSize(1, getUserIdBytes());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream.computeBytesSize(2, getPasswordBytes());
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace() throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest parseFrom(com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest parseFrom(java.io.InputStream input) throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest parseFrom(java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest parseDelimitedFrom(java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest parseFrom(com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() {
return Builder.create();
}
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder(com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return newBuilder(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code auth.AuthRequest}
*
* <pre>
* (1)
* </pre>
*/
public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements
com.bimatrix.revit.nettyProtobuf.Auth.AuthRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.bimatrix.revit.nettyProtobuf.Auth.internal_static_auth_AuthRequest_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() {
return com.bimatrix.revit.nettyProtobuf.Auth.internal_static_auth_AuthRequest_fieldAccessorTable.ensureFieldAccessorsInitialized(
com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest.class, com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest.Builder.class);
}
// Construct using
// com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
userId_ = "";
bitField0_ = (bitField0_ & ~0x00000001);
password_ = "";
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.bimatrix.revit.nettyProtobuf.Auth.internal_static_auth_AuthRequest_descriptor;
}
public com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest getDefaultInstanceForType() {
return com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest.getDefaultInstance();
}
public com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest build() {
com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest buildPartial() {
com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest result = new com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.userId_ = userId_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.password_ = password_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest) {
return mergeFrom((com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest other) {
if (other == com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest.getDefaultInstance())
return this;
if (other.hasUserId()) {
bitField0_ |= 0x00000001;
userId_ = other.userId_;
onChanged();
}
if (other.hasPassword()) {
bitField0_ |= 0x00000002;
password_ = other.password_;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (!hasUserId()) {
return false;
}
if (!hasPassword()) {
return false;
}
return true;
}
public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.bimatrix.revit.nettyProtobuf.Auth.AuthRequest) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
// required string user_id = 1;
private java.lang.Object userId_ = "";
/**
* <code>required string user_id = 1;</code>
*/
public boolean hasUserId() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required string user_id = 1;</code>
*/
public java.lang.String getUserId() {
java.lang.Object ref = userId_;
if (!(ref instanceof java.lang.String)) {
java.lang.String s = ((com.google.protobuf.ByteString) ref).toStringUtf8();
userId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string user_id = 1;</code>
*/
public com.google.protobuf.ByteString getUserIdBytes() {
java.lang.Object ref = userId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
userId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string user_id = 1;</code>
*/
public Builder setUserId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
userId_ = value;
onChanged();
return this;
}
/**
* <code>required string user_id = 1;</code>
*/
public Builder clearUserId() {
bitField0_ = (bitField0_ & ~0x00000001);
userId_ = getDefaultInstance().getUserId();
onChanged();
return this;
}
/**
* <code>required string user_id = 1;</code>
*/
public Builder setUserIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
userId_ = value;
onChanged();
return this;
}
// required string password = 2;
private java.lang.Object password_ = "";
/**
* <code>required string password = 2;</code>
*/
public boolean hasPassword() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string password = 2;</code>
*/
public java.lang.String getPassword() {
java.lang.Object ref = password_;
if (!(ref instanceof java.lang.String)) {
java.lang.String s = ((com.google.protobuf.ByteString) ref).toStringUtf8();
password_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string password = 2;</code>
*/
public com.google.protobuf.ByteString getPasswordBytes() {
java.lang.Object ref = password_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
password_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string password = 2;</code>
*/
public Builder setPassword(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
password_ = value;
onChanged();
return this;
}
/**
* <code>required string password = 2;</code>
*/
public Builder clearPassword() {
bitField0_ = (bitField0_ & ~0x00000002);
password_ = getDefaultInstance().getPassword();
onChanged();
return this;
}
/**
* <code>required string password = 2;</code>
*/
public Builder setPasswordBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
password_ = value;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:auth.AuthRequest)
}
static {
defaultInstance = new AuthRequest(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:auth.AuthRequest)
}
public interface AuthResponseOrBuilder extends com.google.protobuf.MessageOrBuilder {
// required int32 result_code = 1;
/**
* <code>required int32 result_code = 1;</code>
*/
boolean hasResultCode();
/**
* <code>required int32 result_code = 1;</code>
*/
int getResultCode();
// required string result_message = 2;
/**
* <code>required string result_message = 2;</code>
*/
boolean hasResultMessage();
/**
* <code>required string result_message = 2;</code>
*/
java.lang.String getResultMessage();
/**
* <code>required string result_message = 2;</code>
*/
com.google.protobuf.ByteString getResultMessageBytes();
}
/**
* Protobuf type {@code auth.AuthResponse}
*
* <pre>
* (2)
* </pre>
*/
public static final class AuthResponse extends com.google.protobuf.GeneratedMessage implements AuthResponseOrBuilder {
// Use AuthResponse.newBuilder() to construct.
private AuthResponse(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private AuthResponse(boolean noInit) {
this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
private static final AuthResponse defaultInstance;
public static AuthResponse getDefaultInstance() {
return defaultInstance;
}
public AuthResponse getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private AuthResponse(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
case 8: {
bitField0_ |= 0x00000001;
resultCode_ = input.readInt32();
break;
}
case 18: {
bitField0_ |= 0x00000002;
resultMessage_ = input.readBytes();
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.bimatrix.revit.nettyProtobuf.Auth.internal_static_auth_AuthResponse_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() {
return com.bimatrix.revit.nettyProtobuf.Auth.internal_static_auth_AuthResponse_fieldAccessorTable.ensureFieldAccessorsInitialized(
com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse.class, com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse.Builder.class);
}
public static com.google.protobuf.Parser<AuthResponse> PARSER = new com.google.protobuf.AbstractParser<AuthResponse>() {
public AuthResponse parsePartialFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new AuthResponse(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<AuthResponse> getParserForType() {
return PARSER;
}
private int bitField0_;
// required int32 result_code = 1;
public static final int RESULT_CODE_FIELD_NUMBER = 1;
private int resultCode_;
/**
* <code>required int32 result_code = 1;</code>
*/
public boolean hasResultCode() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required int32 result_code = 1;</code>
*/
public int getResultCode() {
return resultCode_;
}
// required string result_message = 2;
public static final int RESULT_MESSAGE_FIELD_NUMBER = 2;
private java.lang.Object resultMessage_;
/**
* <code>required string result_message = 2;</code>
*/
public boolean hasResultMessage() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string result_message = 2;</code>
*/
public java.lang.String getResultMessage() {
java.lang.Object ref = resultMessage_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
resultMessage_ = s;
}
return s;
}
}
/**
* <code>required string result_message = 2;</code>
*/
public com.google.protobuf.ByteString getResultMessageBytes() {
java.lang.Object ref = resultMessage_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
resultMessage_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private void initFields() {
resultCode_ = 0;
resultMessage_ = "";
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1)
return isInitialized == 1;
if (!hasResultCode()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasResultMessage()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeInt32(1, resultCode_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBytes(2, getResultMessageBytes());
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1)
return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(1, resultCode_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream.computeBytesSize(2, getResultMessageBytes());
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace() throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse parseFrom(com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse parseFrom(java.io.InputStream input) throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse parseFrom(java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse parseDelimitedFrom(java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse parseFrom(com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() {
return Builder.create();
}
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder(com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return newBuilder(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code auth.AuthResponse}
*
* <pre>
* (2)
* </pre>
*/
public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements
com.bimatrix.revit.nettyProtobuf.Auth.AuthResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.bimatrix.revit.nettyProtobuf.Auth.internal_static_auth_AuthResponse_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() {
return com.bimatrix.revit.nettyProtobuf.Auth.internal_static_auth_AuthResponse_fieldAccessorTable.ensureFieldAccessorsInitialized(
com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse.class, com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse.Builder.class);
}
// Construct using
// com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
resultCode_ = 0;
bitField0_ = (bitField0_ & ~0x00000001);
resultMessage_ = "";
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.bimatrix.revit.nettyProtobuf.Auth.internal_static_auth_AuthResponse_descriptor;
}
public com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse getDefaultInstanceForType() {
return com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse.getDefaultInstance();
}
public com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse build() {
com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse buildPartial() {
com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse result = new com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.resultCode_ = resultCode_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.resultMessage_ = resultMessage_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse) {
return mergeFrom((com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse other) {
if (other == com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse.getDefaultInstance())
return this;
if (other.hasResultCode()) {
setResultCode(other.getResultCode());
}
if (other.hasResultMessage()) {
bitField0_ |= 0x00000002;
resultMessage_ = other.resultMessage_;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (!hasResultCode()) {
return false;
}
if (!hasResultMessage()) {
return false;
}
return true;
}
public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.bimatrix.revit.nettyProtobuf.Auth.AuthResponse) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
// required int32 result_code = 1;
private int resultCode_;
/**
* <code>required int32 result_code = 1;</code>
*/
public boolean hasResultCode() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required int32 result_code = 1;</code>
*/
public int getResultCode() {
return resultCode_;
}
/**
* <code>required int32 result_code = 1;</code>
*/
public Builder setResultCode(int value) {
bitField0_ |= 0x00000001;
resultCode_ = value;
onChanged();
return this;
}
/**
* <code>required int32 result_code = 1;</code>
*/
public Builder clearResultCode() {
bitField0_ = (bitField0_ & ~0x00000001);
resultCode_ = 0;
onChanged();
return this;
}
// required string result_message = 2;
private java.lang.Object resultMessage_ = "";
/**
* <code>required string result_message = 2;</code>
*/
public boolean hasResultMessage() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string result_message = 2;</code>
*/
public java.lang.String getResultMessage() {
java.lang.Object ref = resultMessage_;
if (!(ref instanceof java.lang.String)) {
java.lang.String s = ((com.google.protobuf.ByteString) ref).toStringUtf8();
resultMessage_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string result_message = 2;</code>
*/
public com.google.protobuf.ByteString getResultMessageBytes() {
java.lang.Object ref = resultMessage_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
resultMessage_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string result_message = 2;</code>
*/
public Builder setResultMessage(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
resultMessage_ = value;
onChanged();
return this;
}
/**
* <code>required string result_message = 2;</code>
*/
public Builder clearResultMessage() {
bitField0_ = (bitField0_ & ~0x00000002);
resultMessage_ = getDefaultInstance().getResultMessage();
onChanged();
return this;
}
/**
* <code>required string result_message = 2;</code>
*/
public Builder setResultMessageBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
resultMessage_ = value;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:auth.AuthResponse)
}
static {
defaultInstance = new AuthResponse(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:auth.AuthResponse)
}
private static com.google.protobuf.Descriptors.Descriptor internal_static_auth_AuthRequest_descriptor;
private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_auth_AuthRequest_fieldAccessorTable;
private static com.google.protobuf.Descriptors.Descriptor internal_static_auth_AuthResponse_descriptor;
private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_auth_AuthResponse_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
static {
java.lang.String[] descriptorData = { "\n\nAuth.proto\022\004auth\"0\n\013AuthRequest\022\017\n\007use"
+ "r_id\030\001 \002(\t\022\020\n\010password\030\002 \002(\t\";\n\014AuthResp"
+ "onse\022\023\n\013result_code\030\001 \002(\005\022\026\n\016result_mess" + "age\030\002 \002(\tB\"\n com.bimatrix.revit.nettyPro" + "tobuf" };
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
internal_static_auth_AuthRequest_descriptor = getDescriptor().getMessageTypes().get(0);
internal_static_auth_AuthRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_auth_AuthRequest_descriptor, new java.lang.String[] { "UserId", "Password", });
internal_static_auth_AuthResponse_descriptor = getDescriptor().getMessageTypes().get(1);
internal_static_auth_AuthResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_auth_AuthResponse_descriptor, new java.lang.String[] { "ResultCode", "ResultMessage", });
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {},
assigner);
}
// @@protoc_insertion_point(outer_class_scope)
}
实际应用中会client端 采集数据大量发送到server 程序中需要存储这个连接服务器的channal
以下原来有个问题 这个记录的channal 要放到 AuthServerInitHandler 利用
AuthServerInitHandler channelActive方法 加入channal记录
channelActive和channelInactive方法
这两个方法分别在新的客户端连接到服务端时触发,我们仅仅是在这两个方法中进行Channel的添加和移除操作,并输出一些内容到控制台而已。
可以修改AuthClientInitHandler如下
package com.bimatrix.revit.nettyProtobuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class AuthClientInitHandler extends ChannelInboundHandlerAdapter{
private Logger logger=Logger.getLogger(AuthClientInitHandler.class.getName());
static final ChannelGroup channels = new DefaultChannelGroup(
GlobalEventExecutor.INSTANCE);
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//logger.log(Level.INFO, "AuthClientInitHandler exceptionCaught");
Auth.AuthRequest request=Auth.AuthRequest.newBuilder()
.setUserId("010203")
.setPassword("abcde")
.build();
List<Auth.AuthRequest> sendData = new ArrayList<Auth.AuthRequest>();
Auth.AuthRequest request1=Auth.AuthRequest.newBuilder()
.setUserId("111")
.setPassword("word")
.build();
sendData.add(request1);
sendData.add(request);
ctx.writeAndFlush(request1);
// for(int i=0;i<100;i++){
// if(i%2==0){
// ctx.writeAndFlush(request1);
// }else{
// ctx.writeAndFlush(request);
// }
//
// }
channels.add(ctx.channel());
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
logger.log(Level.INFO, "AuthClientInitHandler channelRead");
Auth.AuthResponse response=(Auth.AuthResponse)msg;
System.out.println("response: code="+response.getResultCode()+", message="+response.getResultMessage());
//ctx.close();
}
}
相应的可以测试一下 修改AuthClient
的main函数
public static void main(String[] args) {
ExecutorService threadPool = Executors.newSingleThreadExecutor();
threadPool.submit(new Runnable() {
@Override
public void run() {
try {
new AuthClient().connect("127.0.0.1", 5555);
} catch (Exception e) {
e.printStackTrace();
}
}
});
try {
Thread.sleep(5000);// 可能做一些事情
Auth.AuthRequest request=Auth.AuthRequest.newBuilder()
.setUserId("66666")
.setPassword("66666")
.build();
for (io.netty.channel.Channel c : AuthClientInitHandler.channels) {
c.writeAndFlush(request);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
参考 http://blog.csdn.net/erli11/article/details/27213239
http://my.oschina.net/OutOfMemory/blog/294505
http://blog.csdn.net/xuechongyang/article/details/8659739