tomcat支持的websocket服务

更多视频分享

  • 海量视频每日更新


在tomcat7之后的版本,写个websocket服务程序非常容易——

如以下代码所示,当客户端建立了一个连接并发送了一些什么内容到服务器,服务器将每隔两秒返回一个字符串“world”。
之所以演示每两秒返回一次是为了说明这是长连接而不是短连接。

import java.io.IOException;

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

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

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

网页只需要这样写:




    
    Hello WebSocket


    


    

    

调试的时候发现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。

你可能感兴趣的:(转载)