WebSocket实时通讯的自学过程(持续更新)

  • webSocket的两种实现方式
  • 继承Endpoint 基类实现WebSocket
  • 服务端使用注解@ServerEndpoint

1.Spring配置文件applicationContext的配置

<bean id="websocket" class="com.ym.crud.utils.WebsocketEndPoint"/>
    <websocket:handlers>
        <websocket:mapping path="/websocket" handler="websocket" />
        <websocket:handshake-interceptors>
            <bean class="com.ym.crud.utils.HandshakeInterceptor" />
        websocket:handshake-interceptors>
    websocket:handlers>

HandshakeInterceptor.java

package com.ym.crud.utils;

import java.util.Map;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor{  

    @Override  
    public boolean beforeHandshake(ServerHttpRequest request,  
            ServerHttpResponse response, WebSocketHandler wsHandler,  
            Map attributes) throws Exception {  
        System.out.println("Before Handshake");  
        return super.beforeHandshake(request, response, wsHandler, attributes);  
    }  

    @Override  
    public void afterHandshake(ServerHttpRequest request,  
            ServerHttpResponse response, WebSocketHandler wsHandler,  
            Exception ex) {  
        System.out.println("After Handshake");  
        super.afterHandshake(request, response, wsHandler, ex);  
    }  
}

WebsocketEndPoint.java

package com.ym.crud.utils;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class WebsocketEndPoint extends TextWebSocketHandler {  

    @Override  
    protected void handleTextMessage(WebSocketSession session,  
        TextMessage message) throws Exception {  
        super.handleTextMessage(session, message);  
        TextMessage returnMessage = new TextMessage(message.getPayload()+" received at server");  
        session.sendMessage(returnMessage);  
    }  
} 

前端页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
  
<html>  
<head>  
    <title>WebSocket/SockJS Echo Sample (Adapted from Tomcat's echo sample)title>  
    <style type="text/css">  
        #connect-container {  
            float: left;  
            width: 400px  
        }  

        #connect-container div {  
            padding: 5px;  
        }  

        #console-container {  
            float: left;  
            margin-left: 15px;  
            width: 400px;  
        }  

        #console {  
            border: 1px solid #CCCCCC;  
            border-right-color: #999999;  
            border-bottom-color: #999999;  
            height: 170px;  
            overflow-y: scroll;  
            padding: 5px;  
            width: 100%;  
        }  

        #console p {  
            padding: 0;  
            margin: 0;  
        }  
    style>  

    <script src="http://cdn.sockjs.org/sockjs-0.3.min.js">script>  

    <script type="text/javascript">  
        var ws = null;  
        var url = null;  
        var transports = [];  

        function setConnected(connected) {  
            document.getElementById('connect').disabled = connected;  
            document.getElementById('disconnect').disabled = !connected;  
            document.getElementById('echo').disabled = !connected;  
        }  

        function connect() {  
            alert("url:"+url);  
            if (!url) {  
                alert('Select whether to use W3C WebSocket or SockJS');  
                return;  
            }  

            ws = (url.indexOf('sockjs') != -1) ?   
                new SockJS(url, undefined, {protocols_whitelist: transports}) : new WebSocket(url);  

            ws.onopen = function () {  
                setConnected(true);  
                log('Info: connection opened.');  
            };  
            ws.onmessage = function (event) {  
                log('Received: ' + event.data);  
            };  
            ws.onclose = function (event) {  
                setConnected(false);  
                log('Info: connection closed.');  
                log(event);  
            };  
        }  

        function disconnect() {  
            if (ws != null) {  
                ws.close();  
                ws = null;  
            }  
            setConnected(false);  
        }  

        function echo() {  
            if (ws != null) {  
                var message = document.getElementById('message').value;  
                log('Client Sent: ' + message);  
                ws.send(message);  
            } else {  
                alert('connection not established, please connect.');  
            }  
        }  

        function updateUrl(urlPath) {  
            if (urlPath.indexOf('sockjs') != -1) {  
                url = urlPath;  
                document.getElementById('sockJsTransportSelect').style.visibility = 'visible';  
            }  
            else {  
              if (window.location.protocol == 'http:') {  
                  url = 'ws://' + window.location.host + urlPath;  
              } else {  
                  url = 'wss://' + window.location.host + urlPath;  
              }  
              document.getElementById('sockJsTransportSelect').style.visibility = 'hidden';  
            }  
        }  

        function updateTransport(transport) {  
            alert(transport);  
          transports = (transport == 'all') ?  [] : [transport];  
        }  

        function log(message) {  
            var console = document.getElementById('console');  
            var p = document.createElement('p');  
            p.style.wordWrap = 'break-word';  
            p.appendChild(document.createTextNode(message));  
            console.appendChild(p);  
            while (console.childNodes.length > 25) {  
                console.removeChild(console.firstChild);  
            }  
            console.scrollTop = console.scrollHeight;  
        }  
    script>  
head>  
<body>  
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets   
    rely on Javascript being enabled. Please enable  
    Javascript and reload this page!h2>noscript>  
<div>  
    <div id="connect-container">  
        <input id="radio1" type="radio" name="group1" onclick="updateUrl(''/项目名称/websocket');">  
            <label for="radio1">W3C WebSocketlabel>  
        <br>  
        <input id="radio2" type="radio" name="group1" onclick="updateUrl('/项目名称/websocket');">  
            <label for="radio2">SockJSlabel>  
        <div id="sockJsTransportSelect" style="visibility:hidden;">  
            <span>SockJS transport:span>  
            <select onchange="updateTransport(this.value)">  
              <option value="all">alloption>  
              <option value="websocket">websocketoption>  
              <option value="xhr-polling">xhr-pollingoption>  
              <option value="jsonp-polling">jsonp-pollingoption>  
              <option value="xhr-streaming">xhr-streamingoption>  
              <option value="iframe-eventsource">iframe-eventsourceoption>  
              <option value="iframe-htmlfile">iframe-htmlfileoption>  
            select>  
        div>  
        <div>  
            <button id="connect" onclick="connect();">Connectbutton>  
            <button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnectbutton>  
        div>  
        <div>  
            <textarea id="message" style="width: 350px">Here is a message!textarea>  
        div>  
        <div>  
            <button id="echo" onclick="echo();" disabled="disabled">Echo messagebutton>  
        div>  
    div>  
    <div id="console-container">  
        <div id="console">div>  
    div>  
div>  
body>  
html>  

2.类似于Servlet、Controller的注解实现方法

前端页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%--    "/admin/toLogin">  --%>


<html>

    <head>
        <meta name="viewport" content="width=device-width" />
        <title>WebSocket 客户端title>
    head>

    <body>
        <div>
            <input type="button" id="btnConnection" value="连接" />
            <input type="button" id="btnClose" value="关闭" />
            <input type="button" id="btnSend" value="发送" />
        div>
        <script type="text/javascript" src="${APP_PATH}/ssmWebSocket/static/js/jquery-1.12.4.min.js">script>
        <script type="text/javascript">
            var socket;
            if(typeof(WebSocket) == "undefined") {
                alert("您的浏览器不支持WebSocket");
               /*  return; */
            }

            $("#btnConnection").click(function() {
                //实现化WebSocket对象,指定要连接的服务器地址与端口
              socket = new WebSocket("ws://localhost:端口号/项目名称/ws/张三2232");
                //打开事件
                socket.onopen = function() {
                    alert("Socket 已打开");
                    //socket.send("这是来自客户端的消息" + location.href + new Date());
                };
                //获得消息事件
                socket.onmessage = function(msg) {
                    alert(msg.data);
                };
                //关闭事件
                socket.onclose = function() {
                    alert("Socket已关闭");
                };
                //发生了错误事件
                socket.onerror = function() {
                    alert("发生了错误");
                }
            });

            //发送消息
            $("#btnSend").click(function() {
                socket.send("这是来自客户端的消息" + location.href + new Date());
            });

            //关闭
            $("#btnClose").click(function() {
                socket.close();
            });
        script>
    body>

html>

后端代码

package com.ym.crud.controller;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

//ws://127.0.0.1:端口号/Demo1/ws/张三
@ServerEndpoint("/ws/{user}")
public class WSServer {
    private String currentUser;

    //连接打开时执行
    @OnOpen
    public void onOpen(@PathParam("user") String user, Session session) {
        currentUser = user;
        System.out.println("Connected ... " + session.getId());
    }

    //收到消息时执行
    @OnMessage
    public String onMessage(String message, Session session) {
        System.out.println(currentUser + ":" + message);
        return currentUser + ":" + message;
    }

    //连接关闭时执行
    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        System.out.println(String.format("Session %s closed because of %s", session.getId(), closeReason));
    }

    //连接错误时执行
    @OnError
    public void onError(Throwable t) {
        t.printStackTrace();
    }
}

你可能感兴趣的:(java,html5,实时通讯)