jetty和websocket和protobuf

前面两篇文章都在说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;
}






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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值