WebSocket实现

概念

客户端

websocket允许通过JavaScript建立与远程服务器的连接,从而实现客户端与服务器间双向的通信。在websocket中有两个方法:  
    1、send() 向远程服务器发送数据
    2、close() 关闭该websocket链接
  websocket同时还定义了几个监听函数    
    1、onopen 当网络连接建立时触发该事件
    2、onerror 当网络发生错误时触发该事件
    3、onclose 当websocket被关闭时触发该事件
    4、onmessage 当websocket接收到服务器发来的消息的时触发的事件,也是通信中最重要的一个监听事件。msg.data
  websocket还定义了一个readyState属性,这个属性可以返回websocket所处的状态:
    1、CONNECTING(0) websocket正尝试与服务器建立连接
    2、OPEN(1) websocket与服务器已经建立连接
    3、CLOSING(2) websocket正在关闭与服务器的连接
    4、CLOSED(3) websocket已经关闭了与服务器的连接

    

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
    <%@ page import="com.hzm.socialweb.beans.Login"%>
<jsp:useBean id="login" type="com.hzm.socialweb.beans.Login" scope="session"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
    <meta charset="UTF-8">
    <title>Test WebSocket</title>
    <style>
        #chat{
            width:410px;
        }

        #console-container{
            width:410px;
        }

        #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>
        var Chat = {};

        Chat.socket = null;

        Chat.connect = (function(host){
            if('WebSocket' in window){
                Chat.socket = new WebSocket(host);
            }else if('MozWebSocket' in window){
                Chat.socket = new MozWebSocket(host);
            }else{
                Console.log('Error:WebSocket is not supported by this browser.');
                return;
            }

            Chat.socket.onopen = function(){
                Console.log("Info:WebSocket connection opened.");
                document.getElementById('chat').onkeydown = function(event){
                    if(event.keyCode == 13){
                        Chat.sendMessage();
                    }
                }
            }
            Chat.socket.onclose = function(){
                document.getElementById('chat').onkeydown = null;
                Console.log('Info:WebSocket closed.');
            }

            Chat.socket.onmessage = function(message){
                Console.log(message.data);

            }
        }
        );

        Chat.initialize = function(){
            if(window.location.protocol == 'http:'){
                Chat.connect('ws://' + window.location.host + '/SocialWeb/websocket/chat/'+'<jsp:getProperty name="login" property="id" />');

            }else{
                Chat.connect('wss://' + window.location.host + '/SocialWeb/websocket/chat/'+'<jsp:getProperty name="login" property="id" />');
            }
        }

        Chat.sendMessage = (function(){
            var message = document.getElementById("chat").value;
            if(message != ''){
                Chat.socket.send(message);
                document.getElementById('chat').value='';
            }
        })

        var Console = {};
        Console.log = (function(message){
            var console = document.getElementById('console');
            var p = document.createElement('p');
            p.style.wordWrap = "break-word";
            p.innerHTML = message;
            console.appendChild(p);
            while(console.childNodes.length > 25){
                console.removeChild(console.firstChild);
            }
            console.scrollTop = console.scrollHeight;
        })

        Chat.initialize();

    </script>


</head>
<body>
    <div>
        <p>
            <input type="text" placeholder="type and press enter to chat" id="chat" />
        </p>
        <div id="console-container">
            <div id="console">
            </div>
        </div>
    </div>
</body>
</html>

服务端

使用 @ServerEndpoint 注释作为 WebSocket 服务器的端点。如果需要传参,可以使用{参数名}来传参。
例如:@ServerEndpoint(“/文件路径(随意)/{参数名})


package com.hzm.socialweb.servlet;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

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;


@ServerEndpoint(value = "/websocket/chat/{user}")//{user}为传入映射的值

public class ChatAnnotation{


    private static final Set<ChatAnnotation> connections =
            new CopyOnWriteArraySet<ChatAnnotation>();

    private  String nickname;
    String id;

    private Session session;

    @OnOpen
    public void start(@PathParam("user")String user,Session session) {//@PathParam为获取传入映射的值
        this.nickname=user;
        this.session = session;
        connections.add(this);
        String message = String.format("* %s %s", nickname, "has joined.");
        broadcast(message);
    }


    @OnClose
    public void end() {
        connections.remove(this);
        String message = String.format("* %s %s",
                nickname, "has disconnected.");
        broadcast(message);
    }


    @OnMessage
    public void incoming(String message) {
        // Never trust the client
        String filteredMessage = String.format("%s: %s",
                nickname, message);
        broadcast(filteredMessage);
    }




    @OnError
    public void onError(Throwable t) throws Throwable {
        t.printStackTrace();
    }


    private static void broadcast(String msg) {
        for (ChatAnnotation client : connections) {
            try {
                synchronized (client) {
                    client.session.getBasicRemote().sendText(msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
                connections.remove(client);
                try {
                    client.session.close();
                } catch (IOException e1) {
                    // Ignore
                }
                String message = String.format("* %s %s",
                        client.nickname, "has been disconnected.");
                broadcast(message);
            }
        }
    }
}

代码均改自tomcat WebSocket

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值