Skip to content

Commit e011f72

Browse files
committed
Serializing data between client/server
1 parent 51f6d60 commit e011f72

File tree

11 files changed

+176
-74
lines changed

11 files changed

+176
-74
lines changed

client/pom.xml

+7
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,12 @@
1212

1313
<artifactId>client</artifactId>
1414

15+
<dependencies>
16+
<dependency>
17+
<groupId>com.fanavard.challenge</groupId>
18+
<artifactId>core</artifactId>
19+
<version>1.0-SNAPSHOT</version>
20+
</dependency>
21+
</dependencies>
1522

1623
</project>

client/src/main/java/com/fanavard/challenge/client/ClientApplication.java

+6-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import com.fanavard.challenge.client.socket.SocketClient;
44
import org.slf4j.Logger;
55
import org.slf4j.LoggerFactory;
6+
import org.springframework.beans.factory.annotation.Autowired;
67
import org.springframework.stereotype.Component;
78

89
/**
@@ -11,10 +12,14 @@
1112
@Component
1213
public class ClientApplication implements Runnable {
1314
private static final Logger logger = LoggerFactory.getLogger(ClientApplication.class);
15+
16+
@Autowired
17+
SocketClient socketClient;
18+
1419
public void run() {
1520
logger.debug("Starting client");
1621
try {
17-
SocketClient.main(new String[]{});
22+
socketClient.run();
1823
} catch (Exception e) {
1924
e.printStackTrace();
2025
}

client/src/main/java/com/fanavard/challenge/client/socket/SocketClient.java

+54-21
Original file line numberDiff line numberDiff line change
@@ -8,35 +8,68 @@
88
import io.netty.channel.nio.NioEventLoopGroup;
99
import io.netty.channel.socket.SocketChannel;
1010
import io.netty.channel.socket.nio.NioSocketChannel;
11+
import io.netty.handler.codec.serialization.ObjectEncoder;
12+
import org.springframework.beans.factory.annotation.Autowired;
13+
import org.springframework.context.ApplicationContext;
14+
import org.springframework.stereotype.Component;
1115

1216
/**
1317
* Created by ocean on 11/23/15.
1418
*/
19+
@Component
1520
public class SocketClient {
16-
public static void main(String[] args) throws Exception {
17-
String host = "127.0.0.1";
18-
int port = 8080;
19-
EventLoopGroup workerGroup = new NioEventLoopGroup();
21+
private final String host = "127.0.0.1";
22+
private final int port = 8080;
23+
private Bootstrap b;
24+
private NioEventLoopGroup workerGroup;
25+
26+
@Autowired
27+
ApplicationContext context;
28+
29+
public void run() throws Exception {
30+
initialize();
2031

2132
try {
22-
Bootstrap b = new Bootstrap(); // (1)
23-
b.group(workerGroup); // (2)
24-
b.channel(NioSocketChannel.class); // (3)
25-
b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
26-
b.handler(new ChannelInitializer<SocketChannel>() {
27-
@Override
28-
public void initChannel(SocketChannel ch) throws Exception {
29-
ch.pipeline().addLast(new SocketDecoder(), new SocketClientHandler());
30-
}
31-
});
32-
33-
// Start the client.
34-
ChannelFuture f = b.connect(host, port).sync(); // (5)
35-
36-
// Wait until the connection is closed.
37-
f.channel().closeFuture().sync();
33+
configureAndStartServer();
3834
} finally {
39-
workerGroup.shutdownGracefully();
35+
shutdownClient(workerGroup);
4036
}
4137
}
38+
39+
private void configureAndStartServer() throws InterruptedException {
40+
configureServer();
41+
startServer();
42+
}
43+
44+
private void startServer() throws InterruptedException {
45+
// Start the client.
46+
ChannelFuture f = b.connect(host, port).sync(); // (5)
47+
48+
// Wait until the connection is closed.
49+
f.channel().closeFuture().sync();
50+
}
51+
52+
private void configureServer() {
53+
b.group(workerGroup); // (2)
54+
b.channel(NioSocketChannel.class); // (3)
55+
b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
56+
b.handler(new ChannelInitializer<SocketChannel>() {
57+
@Override
58+
public void initChannel(SocketChannel ch) throws Exception {
59+
ch.pipeline().addLast(
60+
new ObjectEncoder(),
61+
context.getBean(SocketClientHandler.class)
62+
);
63+
}
64+
});
65+
}
66+
67+
private void initialize() {
68+
workerGroup = new NioEventLoopGroup();
69+
b = new Bootstrap(); // (1)
70+
}
71+
72+
private void shutdownClient(EventLoopGroup workerGroup) {
73+
workerGroup.shutdownGracefully();
74+
}
4275
}

client/src/main/java/com/fanavard/challenge/client/socket/SocketClientHandler.java

+35-14
Original file line numberDiff line numberDiff line change
@@ -3,37 +3,58 @@
33
/**
44
* Created by ocean on 11/23/15.
55
*/
6+
import com.fanavard.challenge.core.model.UnixTime;
67
import io.netty.buffer.ByteBuf;
8+
import io.netty.buffer.Unpooled;
9+
import io.netty.buffer.WrappedByteBuf;
10+
import io.netty.channel.ChannelFuture;
11+
import io.netty.channel.ChannelFutureListener;
712
import io.netty.channel.ChannelHandlerAdapter;
813
import io.netty.channel.ChannelHandlerContext;
14+
import io.netty.util.CharsetUtil;
15+
import org.springframework.stereotype.Component;
916

17+
import java.io.BufferedOutputStream;
18+
import java.io.ByteArrayOutputStream;
19+
import java.nio.charset.Charset;
1020
import java.util.Date;
21+
import java.util.Scanner;
1122

23+
@Component
1224
public class SocketClientHandler extends ChannelHandlerAdapter {
13-
private ByteBuf buf;
25+
// private ByteBuf buf;
1426

1527
@Override
1628
public void handlerAdded(ChannelHandlerContext ctx) {
17-
buf = ctx.alloc().buffer(4); // (1)
18-
}
29+
// buf = ctx.alloc().buffer(4); // (1)
30+
31+
}
1932

2033
@Override
2134
public void handlerRemoved(ChannelHandlerContext ctx) {
22-
buf.release(); // (1)
23-
buf = null;
35+
// buf.release(); // (1)
36+
// buf = null;
37+
}
38+
39+
@Override
40+
public void channelActive(ChannelHandlerContext ctx) throws Exception {
41+
2442
}
2543

2644
@Override
2745
public void channelRead(ChannelHandlerContext ctx, Object msg) {
28-
ByteBuf m = (ByteBuf) msg;
29-
buf.writeBytes(m); // (2)
30-
m.release();
31-
32-
if (buf.readableBytes() >= 4) { // (3)
33-
long currentTimeMillis = (buf.readUnsignedInt() - 2208988800L) * 1000L;
34-
System.out.println(new Date(currentTimeMillis));
35-
ctx.close();
36-
}
46+
// ByteBuf m = (ByteBuf) msg;
47+
// System.out.println(m.toString(CharsetUtil.UTF_8));
48+
//
49+
ctx.write(msg);
50+
51+
// ByteBuf buffer = Unpooled.copiedBuffer("[3]", CharsetUtil.UTF_8);
52+
// ctx.writeAndFlush(buffer);
53+
}
54+
55+
@Override
56+
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
57+
ctx.flush();
3758
}
3859

3960
@Override

client/src/main/java/com/fanavard/challenge/client/socket/SocketDecoder.java

-25
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package com.fanavard.challenge.core.model;
2+
3+
/**
4+
* Created by ocean on 11/24/15.
5+
*/
6+
public interface Command {
7+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package com.fanavard.challenge.core.model;
2+
3+
/**
4+
* Created by ocean on 11/24/15.
5+
*/
6+
public class InitGameCommand implements Command {
7+
private final int playersCount;
8+
9+
public InitGameCommand(int playersCount) {
10+
this.playersCount = playersCount;
11+
}
12+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.fanavard.challenge.core.model;
2+
3+
/**
4+
* Created by ocean on 11/24/15.
5+
*/
6+
import java.util.Date;
7+
8+
public class UnixTime {
9+
10+
private final long value;
11+
12+
public UnixTime() {
13+
this(System.currentTimeMillis() / 1000L + 2208988800L);
14+
}
15+
16+
public UnixTime(long value) {
17+
this.value = value;
18+
}
19+
20+
public long value() {
21+
return value;
22+
}
23+
24+
@Override
25+
public String toString() {
26+
return new Date((value() - 2208988800L) * 1000L).toString();
27+
}
28+
}

server/pom.xml

+6
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,12 @@
1818
<version>1.0-SNAPSHOT</version>
1919
</dependency>
2020

21+
<dependency>
22+
<groupId>com.fanavard.challenge</groupId>
23+
<artifactId>core</artifactId>
24+
<version>1.0-SNAPSHOT</version>
25+
</dependency>
26+
2127
<dependency>
2228
<groupId>com.fanavard.challenge</groupId>
2329
<artifactId>namefamily</artifactId>

server/src/main/java/com/fanavard/challenge/server/socket/SocketServer.java

+10-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,11 @@
1212
import io.netty.channel.nio.NioEventLoopGroup;
1313
import io.netty.channel.socket.SocketChannel;
1414
import io.netty.channel.socket.nio.NioServerSocketChannel;
15+
import io.netty.handler.codec.serialization.ClassResolver;
16+
import io.netty.handler.codec.serialization.ClassResolvers;
17+
import io.netty.handler.codec.serialization.ObjectDecoder;
1518
import org.springframework.beans.factory.annotation.Autowired;
19+
import org.springframework.context.ApplicationContext;
1620
import org.springframework.stereotype.Component;
1721

1822
@Component
@@ -23,6 +27,9 @@ public class SocketServer {
2327
private EventLoopGroup workerGroup;
2428
private ServerBootstrap serverBootstrap;
2529

30+
@Autowired
31+
ApplicationContext context;
32+
2633
// @Autowired
2734
// SocketServerHandler socketServerHandler;
2835
//
@@ -46,7 +53,9 @@ private void configureServerBootstrap() {
4653
.childHandler(new ChannelInitializer<SocketChannel>() { // (4)
4754
@Override
4855
public void initChannel(SocketChannel ch) throws Exception {
49-
ch.pipeline().addLast(new SocketServerHandler());
56+
ch.pipeline().addLast(
57+
new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)),
58+
new SocketServerHandler());
5059
}
5160
})
5261
.option(ChannelOption.SO_BACKLOG, 128) // (5)

server/src/main/java/com/fanavard/challenge/server/socket/SocketServerHandler.java

+11-12
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,12 @@
55
*/
66
import io.netty.buffer.ByteBuf;
77

8+
import io.netty.buffer.Unpooled;
89
import io.netty.channel.ChannelFuture;
910
import io.netty.channel.ChannelFutureListener;
1011
import io.netty.channel.ChannelHandlerContext;
1112
import io.netty.channel.ChannelHandlerAdapter;
13+
import io.netty.util.CharsetUtil;
1214
import io.netty.util.ReferenceCountUtil;
1315
import org.slf4j.Logger;
1416
import org.slf4j.LoggerFactory;
@@ -22,22 +24,19 @@ public class SocketServerHandler extends ChannelHandlerAdapter { // (1)
2224
private static Logger logger = LoggerFactory.getLogger(SocketServer.class);
2325

2426
@Override
25-
public void channelActive(final ChannelHandlerContext ctx) { // (1)
26-
logger.debug("write time");
27-
final ByteBuf time = ctx.alloc().buffer(4); // (2)
28-
time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L));
27+
public void channelActive(ChannelHandlerContext ctx) throws Exception {
28+
logger.debug("channelActive");
29+
}
2930

30-
final ChannelFuture f = ctx.writeAndFlush(time); // (3)
31-
f.addListener(new ChannelFutureListener() {
32-
public void operationComplete(ChannelFuture future) {
33-
assert f == future;
34-
ctx.close();
35-
}
36-
}); // (4)
31+
@Override
32+
public void channelRead(ChannelHandlerContext ctx, Object msg) {
33+
logger.debug("channelRead");
34+
logger.debug("Server read: {}", msg.getClass());
3735
}
3836

3937
@Override
4038
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
4139
cause.printStackTrace();
4240
ctx.close();
43-
}}
41+
}
42+
}

0 commit comments

Comments
 (0)