【发布时间】:2014-10-31 12:36:16
【问题描述】:
我想做一些简单的聊天。 服务器必须在客户端列表中添加新客户端,并且当一个客户端向服务器发送消息时,服务器必须将此消息重新发送给其他客户端。 我知道如何从客户端读取消息,但我不知道如何将消息从服务器发送到客户端。而且我不确定客户列表应该在哪里,但猜测在处理程序类中。 这是我初始化服务器类的主类
package firstPackage;
public class main {
public static void main(String[] args) throws Exception
{
Server server = new Server(9050);
server.run();
}
}
这里是服务器类
package firstPackage;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
public class Server {
private int port;
public Server(int port)
{
this.port=port;
}
public void run() throws Exception
{
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try{
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception{
ch.pipeline().addLast(new DiscardServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG,128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = b.bind(port).sync();
f.channel().closeFuture().sync();
}
finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
这里是 Handler 类
package firstPackage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
public class DiscardServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf in = (ByteBuf) msg;
try {
while (in.isReadable()) {
System.out.print((char) in.readByte());
System.out.flush();
}
System.out.println();
ctx.writeAndFlush("hey"); // вот здесь я думал, что сообщение будет отправлятся клиенту, от которого я получил сообщение, но не отправляется
} finally {
ReferenceCountUtil.release(msg);
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channel is active");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channel is invactive");
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
System.out.println("handler added");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
其实我现在没有客户端列表,因为我什至不知道这个列表必须包含什么类型的对象,在C#中是Socket对象,那么在Netty中呢?
【问题讨论】: