maven项目添加websocket

最近由于项目业务需求,需要用到websocket来实现即时信息的推送,学习了一下websocket,网上搜了一下学习教程,很多版本看的我云里雾里,最后选择用tomcat提供的最新版本(tomcat

启动可以查看demo)

好了,进入主题

1、新建maven项目 (websocketTest

2.添加websocket依赖的jar包

          <dependency>
            <groupId>javax.websocket</groupId>
            <artifactId>javax.websocket-api</artifactId>
            <version>1.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
        </dependency>

3 客户端代码(用以sp实现为例)ps:在写websocket 地址时一定要注意,ip+端口+项目名+endpoint,本人在写这个时以为url可以随便指定,可就是访问不到后台,浪费了很长时间才找到原因,所以一定要是项目启动后可以访问的路径加上自己定义拦截点。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>websocket client</title>
</head>
<script type="text/javascript">
var ws;
function hello(){
    ws = new WebSocket("ws://localhost:8080/websocketTest/hello");
    ws.onopen = function(evn){
        console.log(evn);
    };
    ws.onmessage = function(evn){
        console.log(evn.data);
        var dv = document.getElementById("dv");
         dv.innerHTML+=evn.data;
    };
    ws.onclose = function(){
        console.log("关闭");
    };
    
};
function subsend(){
    var msg = document.getElementById("msg").value;
    ws.send(msg);
    document.getElementById("msg").value = "";
}
</script>
<body>
    <h2>Hello World!</h2>
    <div id="dv" />
    <input type="button" value="连接" onclick="hello()" />
    <input type="text" id ="msg" /><input type="button" onclick="subsend()" value="发送" />
</body>
</html>

4.后台服务端实现

package websocket;

import java.io.IOException;

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

@ServerEndpoint("/hello")
public class WebsocketTest {
    public WebsocketTest(){
        System.out.println("WebsocketTest..");
    }

    @OnOpen
    public void onopen(Session session){
        System.out.println("连接成功");
        try {
            session.getBasicRemote().sendText("hello client...");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @OnClose
    public void onclose(Session session){
        System.out.println("close....");
        
    }
     @OnMessage      
    public void onsend(Session session,String msg){
        try {
            session.getBasicRemote().sendText("client"+session.getId()+"say:"+msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } 
     
}

最后maven install一下即可,看一下运行界面,链接url请求了一次一直保持通道链接,发送时可以看到url请求并没有重新请求

 

posted @ 2016-05-01 11:20  挖坑大王  阅读(33803)  评论(2编辑  收藏  举报