yywx001 发表于 2017-3-2 08:07:12

WebSocket实践

  基本弄清楚了WebSocket的来龙去脉后,开始了实现WebSocket技术的探索。
  看过一篇文章,测试了八种WebSocket框架性能,得以了解到实现WebSocket技术的框架有:

Netty、Undertow、Jetty、Vert.x、Grizzly、spray-websocket、node.js-websocket/Node.js、Golang

补充下:

作为老牌的servle容器,tomcat实际也可以实现WebSocket技术。
  下面说一下我遇到的一个标准:JSR356标准:

JSR 356,对于WebSocket的的Java API

这标志着所有兼容JAVA EE 7的应用程序都必须实现这个API。

java开发人员不需要关注websocket具体的实现,而只要关注逻辑就可以了。

具体带来的好处是,比如java EE容器,必须实现这个标准,使我们的编码可以统一规范(之前是如果你使用jetty,那么使用jetty的jar包实现websocket是一套API,如果你使用tomcat,那么使用tomcatjar包实现websocket是一套API,而现在统一的使用一套就可以了)。

但是jetty是在9.1版本之后才实现的(起初我的demo项目怎么也访问不到服务端的websocket,是jetty版本过低。),tomcat是在7之后实现的。
  下面是具体实现的代码

1.首先需要引用jar包

scope为provided,为了防止容器本身的websocket音响。


[*]<dependency>
[*]    <groupId>javax</groupId>
[*]    <artifactId>javaee-api</artifactId>
[*]    <version>7.0</version>
[*]    <scope>provided</scope>
[*]</dependency>

  2.服务端的代码:


[*]package com.lanyoung.im.back.ly.websocket;
[*]
[*]import javax.websocket.OnClose;
[*]import javax.websocket.OnMessage;
[*]import javax.websocket.OnOpen;
[*]import javax.websocket.Session;
[*]import javax.websocket.server.ServerEndpoint;
[*]import java.io.IOException;
[*]
[*]@ServerEndpoint("/websocket")
[*]public class WebSocketTest {
[*]
[*]    @OnMessage
[*]    public void onMessage(String message, Session session)
[*]      throws IOException, InterruptedException {
[*]
[*]      // Print the client message for testing purposes
[*]      System.out.println("Received: " + message);
[*]
[*]      // Send the first message to the client
[*]      session.getBasicRemote().sendText("This is the first server message");
[*]
[*]      // Send 3 messages to the client every 5 seconds
[*]      int sentMessages = 0;
[*]      while(sentMessages < 3){
[*]            Thread.sleep(5000);
[*]            session.getBasicRemote().
[*]                sendText("This is an intermediate server message. Count: "
[*]                  + sentMessages);
[*]            sentMessages++;
[*]      }
[*]
[*]      // Send a final message to the client
[*]      session.getBasicRemote().sendText("This is the last server message");
[*]    }
[*]
[*]    @OnOpen
[*]    public void onOpen () {
[*]      System.out.println("Client connected");
[*]    }
[*]
[*]    @OnClose
[*]    public void onClose () {
[*]      System.out.println("Connection closed");
[*]    }
[*]}

  3.客户端代码


[*]<!DOCTYPE html>
[*]<html>
[*]<head>
[*]<title>Testing websockets</title>
[*]</head>
[*]<body>
[*]    <div>
[*]      <input type="submit" value="Start" onclick="start()" />
[*]    </div>
[*]    <div id="messages"></div>
[*]    <script type="text/javascript">
[*]      var webSocket =
[*]            new WebSocket('ws://localhost:8080/websocket');
[*]
[*]      webSocket.onerror = function(event) {
[*]            onError(event)
[*]      };
[*]
[*]      webSocket.onopen = function(event) {
[*]            onOpen(event)
[*]      };
[*]
[*]      webSocket.onmessage = function(event) {
[*]            onMessage(event)
[*]      };
[*]
[*]      function onMessage(event) {
[*]            document.getElementById('messages').innerHTML
[*]                += '<br />' + event.data;
[*]      }
[*]
[*]      function onOpen(event) {
[*]            document.getElementById('messages').innerHTML
[*]                = 'Connection established';
[*]      }
[*]
[*]      function onError(event) {
[*]            alert(event.data);
[*]      }
[*]
[*]      function start() {
[*]            webSocket.send('hello');
[*]            return false;
[*]      }
[*]    </script>
[*]</body>
[*]</html>



来自为知笔记(Wiz)
页: [1]
查看完整版本: WebSocket实践