我尝试通过网络将 POJO“SecureMessageServerClientMessage”发送到客户端。两者都是使用 netty-Framework for Async 创建的。套接字通信。我对 netty 真的很陌生,所以我接受了示例代码并想要更改它,以便它通过网络发送我的 POJO。我知道这是很多代码,但它几乎是它们的示例,但它不起作用..如果有人能告诉我为什么它不起作用,那就太好了..
这是我的课程: 服务器主要:
public final class SecureChatServer {
static final int PORT = Integer.parseInt(System.getProperty("port", "8992"));
public static void main(String[] args) throws Exception {
SelfSignedCertificate ssc = new SelfSignedCertificate();
SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new SecureChatServerInitializer(sslCtx));
b.bind(PORT).sync().channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
SecureChatServerHandler:
public class SecureChatServerHandler extends SimpleChannelInboundHandler<SecureMessageServerClientMessage> {
static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
private ArrayList<SecureMessageServerUser> userList = new ArrayList();
@Override
public void channelActive(final ChannelHandlerContext ctx) {
// Once session is secured, send a greeting and register the channel to the global channel
// list so the channel received the messages from others.
ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(
new GenericFutureListener<Future<Channel>>() {
@Override
public void operationComplete(Future<Channel> future) throws Exception {
channels.add(ctx.channel());
}
});
}
@Override
public void channelRead0(ChannelHandlerContext ctx, SecureMessageServerClientMessage msg ) throws Exception {
System.out.println("Nachricht empfangen!");
System.out.println("Typ: "+msg.getType());
//Send the received message to all channels but the current one.
for (Channel c: channels) {
if (c != ctx.channel()) {
c.writeAndFlush("[" + ctx.channel().remoteAddress() + "] " + msg + '\n');
} else {
c.writeAndFlush("[you] " + msg + '\n');
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
初始化程序(服务器):
public class SecureChatServerInitializer extends ChannelInitializer<SocketChannel> {
private final SslContext sslCtx;
public SecureChatServerInitializer(SslContext sslCtx) {
this.sslCtx = sslCtx;
}
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// Add SSL handler first to encrypt and decrypt everything.
// In this example, we use a bogus certificate in the server side
// and accept any invalid certificates in the client side.
// You will need something more complicated to identify both
// and server in the real world.
pipeline.addLast(sslCtx.newHandler(ch.alloc()));
// On top of the SSL handler, add the text line codec.
pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
pipeline.addLast(new ObjectEncoder());
// and then business logic.
pipeline.addLast(new SecureChatServerHandler());
}
}
这是我的客户的代码:
public final class SecureChatClient {
static final String HOST = System.getProperty("host", "127.0.0.1");
static final int PORT = Integer.parseInt(System.getProperty("port", "8992"));
public static void main(String[] args) throws Exception {
// Configure SSL.
final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class).handler(new SecureChatClientInitializer(sslCtx));
// Start the connection attempt.
Channel ch = b.connect(HOST, PORT).sync().channel();
// Read commands from the stdin.
ChannelFuture lastWriteFuture = null;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (;;) {
String line = in.readLine();
if (line == null) {
break;
}
if("send".equals(line)){
System.out.println("Test");
lastWriteFuture = ch.writeAndFlush(new SecureMessageServerClientMessage(1, "test"));
if(lastWriteFuture.isSuccess()){
System.out.println("Success");
}
}
// Sends the received line to the server.
//lastWriteFuture = ch.writeAndFlush(line + "\r\n");
// If user typed the 'bye' command, wait until the server closes
// the connection.
if ("bye".equals(line.toLowerCase())) {
ch.closeFuture().sync();
break;
}
}
// Wait until all messages are flushed before closing the channel.
if (lastWriteFuture != null) {
lastWriteFuture.sync();
}
} finally {
// The connection is closed automatically on shutdown.
group.shutdownGracefully();
}
}
}
这里的处理程序:
public class SecureChatClientHandler extends SimpleChannelInboundHandler<SecureMessageServerClientMessage> {
@Override
public void channelRead0(ChannelHandlerContext ctx, SecureMessageServerClientMessage msg) throws Exception {
System.err.println(msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
最后是我的 POJO:
public class SecureMessageServerClientMessage implements Serializable{
private String message;
private int type;
static final int LISTUSER = 0, MESSAGE = 1, LOGOUT = 2, LOGIN = 3;
private String sender;
private String empfaenger;
private ArrayList<SecureMessageServerUser> userList = new ArrayList();
//Erste MSG, Login am Server
public SecureMessageServerClientMessage(int type, String sender){
this.type=type;
this.sender=sender;
}
//Nur für den Clienten, als Anfrage für die user-List
public SecureMessageServerClientMessage(int type){
this.type=type;
}
//Für MessageTyp 0 - LISTUSER, es wird nur die aktuelle User-Liste übertragen
public SecureMessageServerClientMessage(int type, ArrayList userList){
this.userList=userList;
}
//Für MessageTyp 1 - MESSAGE Es wird der Empfänger, und die Nachricht übertragen
public SecureMessageServerClientMessage(int type, String message, String empfaenger, String sender){
this.type=type;
this.message=message;
this.sender=sender;
this.empfaenger=empfaenger;
}
//Für MessageTyp 1 - Msg, die weitergeleitet werden
public SecureMessageServerClientMessage(int type, String message, String sender){
this.type=type;
this.message=message;
this.sender=sender;
}
public String getMessage(){
return this.message;
}
public int getType(){
return type;
}
public String getSender(){
return this.sender;
}
public ArrayList getList() {
return userList;
}
public ArrayList getUserList() {
return userList;
}
public String getEmpfaenger(){
return this.empfaenger;
}
}