tomcat支持的websocket服务

首发:我的博客javascript

在tomcat7以后的版本,写个websocket服务程序很是容易——
如如下代码所示,当客户端创建了一个链接并发送了一些什么内容到服务器,服务器将每隔两秒返回一个字符串“world”。
之因此演示每两秒返回一次是为了说明这是长链接而不是短链接。html

import java.io.IOException;java

import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;web

@ServerEndpoint("/test")
public class MyTest {spring

    @OnMessage
    public void onMessage(String message, Session session) 
        throws IOException, InterruptedException {
        System.out.println("客户端说:" + message);
        
        while(true){
            session.getBasicRemote().sendText("world");
            Thread.sleep(2000);
        }
    }
    
}tomcat

网页只须要这样写:服务器

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Hello WebSocket</title>
</head>
<body>
    <div id="content"></div>
    <button onclick="sayHello()">打招呼</button>websocket

    <script type="text/javascript">
        var webSocket = 
            new WebSocket('ws://localhost:8080/dyna/test');session

        webSocket.onerror = function(event) {
            onError(event)
        };并发

        webSocket.onopen = function(event) {
            onOpen(event)
        };

        webSocket.onmessage = function(event) {
            onMessage(event)
        };

        function onMessage(event) {
            document.getElementById('content').innerHTML += '<br />服务器说:' + event.data;
        }

        function onOpen(event) {
            document.getElementById('content').innerHTML = '链接成功';
        }

        function onError(event) {
            document.getElementById('content').innerHTML = '出现错误';
        }

        function sayHello() {
            webSocket.send('hello');
            return false;
        }
    </script>
</body>
</html>

调试的时候发现tomcat7的支持不是特别好,
在eclipse里添加server而后在上面跑项目,不支持websocket;
用在server.xml里添项目的方式,也不支持websocket。

因此换成tomcat8,在eclipse里添加server而后跑项目,websocket也好使。
这样调试就很方便了。


TODO:
1.maven的tomcat7:run个别项目出现奇怪的问题;maven集成tomcat8的实验有时间作作
2.spring4对websocket的支持怎么试都不成功,有时间攻克它。
3.把今天学的即便通信技术与websocket结合,作网页版qq之类的demo。

长期欢迎项目合做机会介绍,项目收入10%用于酬谢介绍人。新浪微博:@冷镜,QQ:908789432。

相关文章
相关标签/搜索