从Netty SocketServer获取日期

时间:2015-07-01 08:15:24

标签: java sockets netty

我有一个通过Netty.io创建的简单套接字服务器,当我从终端写东西时,一切都像魅力一样。但我也有一个自定义套接字客户端,不使用netty.io,以及如何从netty服务器获取数据?这是我的网络处理程序:

public class DiscardServerHandler extends SimpleChannelInboundHandler<String> {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String message) throws Exception {
        String msg = message;
        try {
            System.out.println(msg);
            System.out.flush();
            ctx.writeAndFlush("Response from server");
        } finally {
            ReferenceCountUtil.retain(msg);
        }
    }

}

这是我的客户端套接字类:

public class ClientSideSocket2 {
    public static void main(String[] args) {
        String serverName = "localhost";
        int port = 9999;
        String line = "";
        Socket client = null;
        PrintWriter toServer = null;
        BufferedReader fromServer = null;

        try {
            System.out.println("Connecting to " + serverName + " on port " + port);
            client = new Socket(serverName, port);
            System.out.println("Just connected to " + client.getRemoteSocketAddress());

            toServer = new PrintWriter(client.getOutputStream(), true);
            fromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));

            for (int i = 0; i < 6; i++) {
                toServer.println("simple string: " + i);
                if ((line = fromServer.readLine()) != null) {
                    System.out.println("Responce from server: " + line);
                }
            }           

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                toServer.close();
                fromServer.close();
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

我无法从第if ((line = fromServer.readLine()) != null)行读取数据。还有其他办法吗?

1 个答案:

答案 0 :(得分:2)

首先,我假设您正确设置ChannelPipeline并触发channelRead0fromServer.readLine()被阻止,它会读取换行符('\ n'),回车符('\ r')或回车后跟一个换行符。

然后问题是你应该回复

ctx.writeAndFlush("Response from server\n");

如果事件未触发,请尝试以这种方式设置ChannelPipeline

ch.pipeline().addLast(
    new StringDecoder(),
    new StringEncoder(),
    new DiscardServerHandler());

然后终止响应的字符串,您的客户端将正常工作。