Skip to content

Commit 448e3e7

Browse files
committed
Netty学习:EchoServer & EchoClient
1 parent c24a8bf commit 448e3e7

10 files changed

Lines changed: 204 additions & 1 deletion

bin/start.sh

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ do
1515
done
1616
APP_CLASSPATH=$APP_CLASSPATH:$APP_HOME/classes
1717

18-
PARAMS=$1' '$2
18+
PARAMS=$*
1919
EXEC='java -Djava.util.logging.config.file='$APP_HOME'/classes/logging.properties -Dfile.encoding=UTF-8 -classpath '$APP_CLASSPATH' '$PARAMS
20+
echo $EXEC
2021
exec $EXEC

bin/startNettyEchoClient.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
source ./start.sh cn.aofeng.demo.netty40x.echo.EchoClient 192.168.56.102 8080

bin/startNettyEchoServer.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
source ./start.sh cn.aofeng.demo.netty40x.echo.EchoServer 8080

lib/commons-lang-2.6.jar

278 KB
Binary file not shown.

lib/netty-3.6.6.Final.jar

-1.15 MB
Binary file not shown.
2.03 MB
Binary file not shown.
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package cn.aofeng.demo.netty40x.echo;
2+
3+
import io.netty.bootstrap.Bootstrap;
4+
import io.netty.channel.ChannelFuture;
5+
import io.netty.channel.ChannelOption;
6+
import io.netty.channel.EventLoopGroup;
7+
import io.netty.channel.nio.NioEventLoopGroup;
8+
import io.netty.channel.socket.nio.NioSocketChannel;
9+
10+
import org.apache.commons.lang.math.NumberUtils;
11+
import org.apache.log4j.Logger;
12+
13+
/**
14+
* Echo客户端。
15+
*
16+
* @author <a href="mailto:[email protected]">聂勇</a>
17+
*/
18+
public class EchoClient {
19+
20+
private static Logger _logger = Logger.getLogger(EchoClient.class);
21+
22+
public void start(String host, int port) {
23+
EventLoopGroup worker = new NioEventLoopGroup(1);
24+
Bootstrap bootstrap = new Bootstrap();
25+
try {
26+
bootstrap.group(worker)
27+
.channel(NioSocketChannel.class)
28+
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000)
29+
.handler(new EchoClientHandler())
30+
.remoteAddress(host, port);
31+
ChannelFuture cf = bootstrap.connect().sync();
32+
cf.channel().closeFuture().sync();
33+
} catch (Exception e) {
34+
_logger.error("occurs error", e);
35+
} finally {
36+
worker.shutdownGracefully();
37+
}
38+
}
39+
40+
/**
41+
* @param args
42+
*/
43+
public static void main(String[] args) {
44+
if (args.length != 2) {
45+
_logger.error("Invalid arguments。Usage:/njava cn.aofeng.demo.netty40x.echo.EchoClient 192.168.56.102 8080");
46+
System.exit(-1);
47+
}
48+
49+
String host = args[0];
50+
int port = NumberUtils.toInt(args[1], 8080);
51+
EchoClient client = new EchoClient();
52+
client.start(host, port);
53+
}
54+
55+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package cn.aofeng.demo.netty40x.echo;
2+
3+
import java.nio.charset.Charset;
4+
import java.text.DateFormat;
5+
import java.text.SimpleDateFormat;
6+
import java.util.Date;
7+
8+
import org.apache.log4j.Logger;
9+
10+
import io.netty.buffer.ByteBuf;
11+
import io.netty.buffer.Unpooled;
12+
import io.netty.channel.ChannelHandlerContext;
13+
import io.netty.channel.ChannelInboundHandlerAdapter;
14+
import io.netty.util.CharsetUtil;
15+
16+
/**
17+
* 发送数据给服务端,并接收服务端的数据。
18+
*
19+
* @author <a href="mailto:[email protected]">聂勇</a>
20+
*/
21+
public class EchoClientHandler extends ChannelInboundHandlerAdapter {
22+
23+
private static Logger _logger = Logger.getLogger(EchoClientHandler.class);
24+
25+
private final Charset _utf8 = CharsetUtil.UTF_8;
26+
27+
public void channelActive(ChannelHandlerContext ctx) {
28+
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ");
29+
String currTimeStr = format.format(new Date());
30+
String data = String.format("Hello, current time is %s", currTimeStr);
31+
ctx.writeAndFlush( Unpooled.copiedBuffer(data, _utf8) );
32+
_logger.info( String.format("Client send data:%s", data) );
33+
}
34+
35+
public void channelRead(ChannelHandlerContext ctx, Object msg) {
36+
ByteBuf inData = (ByteBuf) msg;
37+
_logger.info( String.format("Client receive data:%s", inData.toString(_utf8)) );
38+
}
39+
40+
public void channelReadComplete(ChannelHandlerContext ctx) {
41+
ctx.close();
42+
}
43+
44+
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
45+
_logger.error("occurs error", cause);
46+
ctx.close();
47+
}
48+
49+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package cn.aofeng.demo.netty40x.echo;
2+
3+
import io.netty.bootstrap.ServerBootstrap;
4+
import io.netty.channel.ChannelFuture;
5+
import io.netty.channel.ChannelOption;
6+
import io.netty.channel.EventLoopGroup;
7+
import io.netty.channel.nio.NioEventLoopGroup;
8+
import io.netty.channel.socket.nio.NioServerSocketChannel;
9+
10+
import org.apache.commons.lang.math.NumberUtils;
11+
import org.apache.log4j.Logger;
12+
13+
/**
14+
* Echo服务端:将客户端发送的请求原样返回。
15+
*
16+
* @author <a href="mailto:[email protected]">聂勇</a>
17+
*/
18+
public class EchoServer {
19+
20+
private static Logger _logger = Logger.getLogger(EchoServer.class);
21+
22+
public void start(int port) {
23+
EventLoopGroup boss = new NioEventLoopGroup(1);
24+
EventLoopGroup worker = new NioEventLoopGroup(10);
25+
ServerBootstrap bootstrap = new ServerBootstrap();
26+
try {
27+
bootstrap.group(boss, worker)
28+
.channel(NioServerSocketChannel.class)
29+
.option(ChannelOption.SO_BACKLOG, 128)
30+
.childHandler(new EchoServerHandler())
31+
.localAddress(port);
32+
ChannelFuture bindFuture = bootstrap.bind().sync();
33+
ChannelFuture closeFuture = bindFuture.channel().closeFuture().sync();
34+
_logger.info( String.format("%s started and listen on %s", this.getClass().getSimpleName(), closeFuture ) );
35+
} catch(Exception ex) {
36+
_logger.info( String.format("%s start failed", this.getClass().getSimpleName()), ex);
37+
} finally {
38+
boss.shutdownGracefully();
39+
worker.shutdownGracefully();
40+
}
41+
42+
}
43+
44+
/**
45+
* @param args
46+
*/
47+
public static void main(String[] args) {
48+
if (args.length != 1) {
49+
_logger.error("Invalid arguments。Usage:/njava cn.aofeng.demo.netty40x.echo.EchoServer 8080");
50+
System.exit(-1);
51+
}
52+
53+
int port = NumberUtils.toInt(args[0], 8080);
54+
EchoServer server = new EchoServer();
55+
server.start(port);
56+
}
57+
58+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package cn.aofeng.demo.netty40x.echo;
2+
3+
import java.nio.charset.Charset;
4+
5+
import org.apache.log4j.Logger;
6+
7+
import io.netty.buffer.ByteBuf;
8+
import io.netty.channel.ChannelHandlerContext;
9+
import io.netty.channel.ChannelInboundHandlerAdapter;
10+
import io.netty.channel.ChannelHandler.Sharable;
11+
12+
/**
13+
* 将接收到的数据原样返回给发送方。
14+
*
15+
* @author <a href="mailto:[email protected]">聂勇</a>
16+
*/
17+
@Sharable
18+
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
19+
20+
private static Logger _logger = Logger.getLogger(EchoServerHandler.class);
21+
22+
public void channelRead(ChannelHandlerContext ctx, Object msg) {
23+
ByteBuf inData = (ByteBuf) msg;
24+
String str = inData.toString(Charset.forName("UTF-8"));
25+
_logger.info( String.format("Server receive data:%s", str) );
26+
ctx.write(inData);
27+
}
28+
29+
public void channelReadComplete(ChannelHandlerContext ctx) {
30+
ctx.flush().close();
31+
}
32+
33+
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
34+
_logger.error("occurs error", cause);
35+
ctx.close();
36+
}
37+
38+
}

0 commit comments

Comments
 (0)