Repository navigation
Expand file tree
/
Copy pathNettyServerHandler.java
More file actions
83 lines (71 loc) · 2.32 KB
/
Copy pathNettyServerHandler.java
File metadata and controls
83 lines (71 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package netty;
import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import serialization.object.Person;
import java.net.InetAddress;
/**
* <p>
* 使用hessian2序列化返回消息给客户端
* </p>
* Created by pomelo on 16/10/21.
*/
@ChannelHandler.Sharable // 单例实现注解
public class NettyServerHandler extends SimpleChannelInboundHandler<Object> {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("client connect server success.");
ctx.write("Welcome to " + InetAddress.getLocalHost().getHostName() + "!");
ctx.flush();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
System.out.println("client left server.");
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
super.channelRegistered(ctx);
System.out.println("client register in server.");
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
super.channelUnregistered(ctx);
System.out.println("client unregister server.");
}
/**
* 使用hessian2序列化返回消息给客户端
*
* @param channelHandlerContext
* @param s
* @throws Exception
*/
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object s) throws Exception {
// 回消息给client
System.out.println("received client message: " + s.toString());
channelHandlerContext.write(buildString(s.toString()));
channelHandlerContext.flush();
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
/**
* @param s 字符串
* @return String
*/
private String buildString(String s){
Person person = new Person();
person.setId(1111);
person.setName(s);
person.setEmail("server@qq.com");
return JSON.toJSONString(person);
}
}