WebSocket 1.0的学习和简单使用

WebSocket JavaScript API(client)

<script>
    var URL = "ws://localhost:8080/WebSocketChatRoom/chatRoomServer";
    var websocket;
    var userName;

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

    function connect() {

        if(‘WebSocket‘ in window){
            websocket = new WebSocket(URL);
        }else if(‘MozWebSocket‘ in window){
            websocket = new MozWebSocket(URL);
        }else{
            alert("您的浏览器不支持WebSocket,请更换最新版本浏览器");
            return;
        }

        websocket.onopen = function (evnt) {
            userName = document.getElementById(‘userId‘).value;
            if(userName == ""){
                alert("用户名不能为空");
                return;
            }else{
                setConnected(true);
                websocket.send(userName + "加入聊天室");
            }
        };
        websocket.onmessage = function (evnt) {
            onMessage(evnt)
        };
        websocket.onerror = function (evnt) {
            onError(evnt)
        };
        websocket.onclose = function (evnt) {
            disconnect(evnt);
        }
    }
    function sendMessage() {
        var userName = document.getElementById(‘userId‘).value;
        var msg = document.getElementById(‘message‘).value;
        websocket.send(userName+": "+msg);

    }
    function onMessage(evnt) {
        if (typeof evnt.data == "string") {
            log(evnt.data);
        }
    }
    function onError(evnt) {
        log(‘错误: ‘ + evnt.data);
    }
    /*function onClose(evnt) {
        setConnected(false);
    }*/
    function disconnect(evnt) {
        if(websocket != null){
            websocket.close(1000, userName + "退出聊天室");
            websocket = null;
            log("你已退出聊天室");
            setConnected(false);
        }

    }
    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>
  • websocket.onopen #当打开一个新的连接时会调用这个方法
  • websocket.onmessage #当server有数据返回时调用
  • websocket.send() #向服务端发送信息,类型包括{String|ArrayBuffer|ArrayBufferView|Blob}
  • websocket.close() #向服务器发送关闭的请求,参数{number} [code]  {string} [reason],附相关代码表,一般使用本方法关闭code为1000,直接关闭浏览器为1006,CLOSE_ABNORMAL
Status code Name Description
0-999   Reserved and not used.
1000 CLOSE_NORMAL Normal closure; the connection successfully completed whatever purpose for which it was created.
1001 CLOSE_GOING_AWAY The endpoint is going away, either because of a server failure or because the browser is navigating away from the page that opened the connection.
1002 CLOSE_PROTOCOL_ERROR The endpoint is terminating the connection due to a protocol error.
1003 CLOSE_UNSUPPORTED The connection is being terminated because the endpoint received data of a type it cannot accept (for example, a text-only endpoint received binary data).
1004   Reserved. A meaning might be defined in the future.
1005 CLOSE_NO_STATUS Reserved.  Indicates that no status code was provided even though one was expected.
1006 CLOSE_ABNORMAL Reserved. Used to indicate that a connection was closed abnormally (that is, with no close frame being sent) when a status code is expected.
1007   The endpoint is terminating the connection because a message was received that contained inconsistent data (e.g., non-UTF-8 data within a text message).
1008   The endpoint is terminating the connection because it received a message that violates it‘s policy. This is a generic status code, used when codes 1003 and 1009 are not suitable.
1009 CLOSE_TOO_LARGE The endpoint is terminating the connection because a data frame was received that is too large.
1010   The client is terminating the connection because it expected the server to negotiate one or more extension, but the server didn‘t.
1011   The server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.
1012-1014   Reserved for future use by the WebSocket standard.
1015   Reserved. Indicates that the connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can‘t be verified).
1016-1999   Reserved for future use by the WebSocket standard.
2000-2999   Reserved for use by WebSocket extensions.
3000-3999   Available for use by libraries and frameworks. May not be used by applications.
4000-4999   Available for use by applications.

WebSocket Java API(Server)

@ServerEndpoint("/chatRoomServer")
public class MessageEndPoint {

    private static final ArrayList<Session> sessions;

    static {
        sessions = new ArrayList<Session>();
    }

    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
    }

    @OnMessage
    public void onMessage(String message) {
        sendMessage(message);
    }

    @OnClose
    public void onClose(Session session,CloseReason closeReason) {
        sessions.remove(session);
        sendMessage(closeReason.getReasonPhrase());
    }

    private void sendMessage(String message){
        for(Session session : sessions){
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
  • @ServerEndpoint("/chatRoomServer"),ServerEndpoint把一个POJO类转换成了WebSocket EndPoint,后边的值是访问地址
  • 关于注解请看
Annotation Role

@ServerEndpoint


Declare a Server Endpoint


@ClientEndpoint


Declare a Client Endpoint


@OnOpen


Declare this method handles open events


@OnMessage


Declare this method handles Websocket messages


@OnError


Declare this method handles error


@OnClose


Declare this method handles WebSocket close events

<dependency>
          <groupId>javax.websocket</groupId>
          <artifactId>javax.websocket-api</artifactId>
          <version>1.0</version>
          <scope>provided</scope>
      </dependency>

我使用的tomcat,<scope>provided</scope>这句一定要加上,否则会报404,tomcat中有相关重复的类

WebSocket 1.0的学习和简单使用

时间: 2024-07-31 00:58:31

WebSocket 1.0的学习和简单使用的相关文章

(原创)cocos2d-x 3.0+ lua 学习和工作(2) : 单一继承简单介绍

-- 星月相随倾心贡献~~~ -- 本章简单介绍一下:单一继承 -- 多继承本人还没有用过,主要是lua多继承感觉不好用~~~个人感觉~~~大汗~! -- example: local Base = class( "Base" ) Base.__index = Base function Base:ctor(...) print( self.__cname ) -- 输出:类名字.class( "xxx" ), self._cname 就是 xxx end func

mjson学习的简单例子分享

01#include <mjson/json.h>02#include <stdio.h>03#include <stdlib.h>04int main()05{06    json_t *entry, *root, *head, *body, *label, *value;07    char *document;08    root = json_new_object();09     10    /*--------Head------*/11 12    hea

(原创) cocos2d-x 3.0+ lua 学习和工作(4) : 公共函数(5): 返回指定表格中的所有键(key):table.keys

这里的函数主要用来做:返回指定表格中所有的键.参考资料为quick_cocos. 星月倾心贡献~~~ --[[ -- 返回指定表格中的所有键(key) -- example: local t = ( a = 1, b = 2, c = 3 ) local keys = table.keys( t ) -- keys = { "a", "b", "c" } -- @param t 要检查的表格(t表示是table) -- @param table

【转载】从0开始学习 GITHUB 系列之「向GITHUB 提交代码」

转载自http://stormzhang.com 之前的这篇文章「从0开始学习 GitHub 系列之「Git速成」」相信大家都已经对 Git 的基本操作熟悉了,但是这篇文章只介绍了对本地 Git 仓库的基本操作,今天我就来介绍下如何跟远程仓库一起协作,教你们向 GitHub 上提交你们的第一行代码! 1. SSH 你拥有了一个 GitHub 账号之后,就可以自由的 clone 或者下载其他项目,也可以创建自己的项目,但是你没法提交代码.仔细想想也知道,肯定不可能随意就能提交代码的,如果随意可以提

mysql 5.0存储过程学习总结

mysql存储过程的创建,删除,调用及其他常用命令 本人qq群也有许多的技术文档,希望可以为你提供一些帮助(非技术的勿加). QQ群:   281442983 (点击链接加入群:http://jq.qq.com/?_wv=1027&k=29LoD19)  mysql 5.0存储过程学习总结 一.创建存储过程 1.基本语法: create procedure sp_name()begin………end 2.参数传递 二.调用存储过程 1.基本语法:call sp_name()注意:存储过程名称后面必

(原创) cocos2d-x 3.0+ lua 学习和工作(5) : table的remove的坑

本章主要讲下,table的remove,这个东西不注意就容易被坑(被坑的飘过~~~),当然,这里是针对数组table.即用ipairs方法遍历. 星月倾心贡献~~~ 看示例1:直接nil local tbl = { 1, 2, 3, 4, 5 } for k, v in ipairs( tbl ) do if v == 3 then tbl[k] = nil else print( "one: " .. k .. ":" .. v ) end end -- 再次输出

(原创) cocos2d-x 3.0+ lua 学习和工作(4) : 公共函数(4): handler

这里的函数主要用来做:回调函数.参考资料为quick_cocos. 星月倾心贡献~~~ --[[ -- 将lua对象及方法包装为一个匿名函数 -- 许多功能需要传入一个 Lua 函数做参数,然后在特定事件发生时就会调用传入的函数.例如触摸事件.帧事件等等. -- example: local MyScene = class( "MyScene", function() ) return cc.Layer:create() end ) function MyScene:ctor() se

hadoop1.0.3学习笔记

回 到 目 录 最近要从网上抓取数据下来,然后hadoop来做存储和分析.每晚尽量更新 呆毛王赛高 月子酱赛高 小唯酱赛高 目录 安装hadoop1.0.3 HDFS wordcount mapreduce去重 mapreduce算平均分 mapreduce排序 安装hadoop1.0.3 1 ubuntu中安装hadoop 1.0.3 2 ------------伪分布式安装------------- 3 1.安装ssh 4 sudo apt-get install openssh-serve

[Python]webservice 学习(1) -- 简单服务和调用

由于项目中需要用到webservice来做接口,于是花点时间先做知识储备. 开始的时候觉着这个webservice就是一个http请求啊,服务端监听,客户端发送xml报文,然后解析下发送了什么内容,返回响应的数据. 这是百度百科对webservice的定义,一般使用wsdl来描述服务. 后来我的误区就是 wsdl的xml  和 用http 请求组成的xml也就是用soap来请求webservice, 这两种xml为啥不一样... 困惑: 看了些资料以后才明白,wsdl就是你发布的webservi