netty java client_NettyClient.java

package com.chen;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.InetSocketAddress;

import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;

import org.jboss.netty.channel.ChannelFuture;

import org.jboss.netty.channel.ChannelHandlerContext;

import org.jboss.netty.channel.ChannelPipeline;

import org.jboss.netty.channel.ChannelPipelineFactory;

import org.jboss.netty.channel.ChannelStateEvent;

import org.jboss.netty.channel.Channels;

import org.jboss.netty.channel.MessageEvent;

import org.jboss.netty.channel.SimpleChannelHandler;

import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

import org.jboss.netty.handler.codec.string.StringDecoder;

import org.jboss.netty.handler.codec.string.StringEncoder;

public class NettyClient {

public static void main(String[] args) {

// Configure the client.

ClientBootstrap bootstrap = new ClientBootstrap(

new NioClientSocketChannelFactory(

Executors.newCachedThreadPool(),

Executors.newCachedThreadPool()));

// Set up the default event pipeline.

bootstrap.setPipelineFactory(new ChannelPipelineFactory() {

@Override

public ChannelPipeline getPipeline() throws Exception {

return Channels.pipeline(new StringDecoder(),

new StringEncoder(), new ClientHandler());

}

});

// Start the connection attempt.

ChannelFuture future = bootstrap.connect(new InetSocketAddress(

"localhost", 8000));

// Wait until the connection is closed or the connection attempt fails.

future.getChannel().getCloseFuture().awaitUninterruptibly();

// Shut down thread pools to exit.

bootstrap.releaseExternalResources();

}

private static class ClientHandler extends SimpleChannelHandler {

private BufferedReader sin = new BufferedReader(new InputStreamReader(

System.in));

@Override

public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)

throws Exception {

if (e.getMessage() instanceof String) {

String message = (String) e.getMessage();

System.out.println(message);

e.getChannel().write(sin.readLine());

System.out.println("\n等待客户端输入。。。");

}

super.messageReceived(ctx, e);

}

@Override

public void channelConnected(ChannelHandlerContext ctx,

ChannelStateEvent e) throws Exception {

System.out.println("已经与Server建立连接。。。。");

System.out.println("\n请输入要发送的信息:");

super.channelConnected(ctx, e);

e.getChannel().write(sin.readLine());

}

}

}

一键复制

编辑

Web IDE

原始数据

按行查看

历史

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值