|
前面两篇文章都在说protobuf,这里说下我使用的服务器环境:
jetty-distribution-9.1.0.v20131115 + JDK7 + protobuf 2.5.0 +apache-maven-3.1.1
首先需要编译protobuf的java库文件,具体请参考protobuf目录下的java/README.txt文件
生成java用的protobuf文件的方法请参考官方文档
1.说下jetty下的websocket是如何实现的,新建TestWebSocket实现WebSocketListener接口:
public class TestWebSocket implements WebSocketListener {
@Override
public void onWebSocketBinary(byte[] payload, int offset, int len) {
System.out.println("receive message binary ...");
try {
Test.Message msg = Test.Message.parseFrom(payload);
switch(msg.getId()){
case 101:
Test.Person person = Test.Person.parseFrom(msg.getData().getBytes());
System.out.println(person.getId());
System.out.println(person.getName());
System.out.println(person.getEmail());
break;
}
} catch (InvalidProtocolBufferException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onWebSocketClose(int statusCode, String reason) {
System.out.println("socket closed. status code:" + statusCode
+ " reason:" + reason);
}
@Override
public void onWebSocketConnect(Session session) {
System.out.println("new connect ...");
}
@Override
public void onWebSocketError(Throwable error) {
System.out.println("error...");
}
@Override
public void onWebSocketText(String message) {
System.out.println("receive message text ...");
}
}2.新建WebSocketTestServlet类集成WebSocketServlet类:
public class WebSocketTestServlet extends WebSocketServlet {
private static final long serialVersionUID = -2964802839253009970L;
@Override
public void configure(WebSocketServletFactory factory) {
factory.register(TestWebSocket.class);
}
}3.Main方法:
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler(
ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
context.addServlet(new ServletHolder(new WebSocketTestServlet()), "/web");
server.start();
server.join();
}4.运行即可启动服务器进行测试。 另外贴上我使用的test.proto文件的内容(前面两个文档用的都是这个文件来做的测试):
package cn.wey.test;
message Message {
required int32 id = 1;
optional string data = 2;
}
message Person {
required int32 id = 1;
required string name = 2;
optional string email = 3;
}
|
|
|
|
|
|
|