`

websocket

阅读更多
http://haoningabc.iteye.com/blog/2169054 web介绍 web介绍
一、客户端
1.var ws = new WebSocket(“ws://localhost:8080”);
申请一个WebSocket对象,参数是需要连接的服务器端的地址,同http协议使用http://开头一样,WebSocket协议的URL使用ws://开头,另外安全的WebSocket协议使用wss://开头。
ws.send(“hello”);
用于叫消息发送到服务端

2.ws.onopen = function() { console.log(“open”)};
当websocket创建成功时,即会触发onopen事件

3.ws.onmessage = function(evt) { console.log(evt.data) };
当客户端收到服务端发来的消息时,会触发onmessage事件,参数evt.data中包含server传输过来的数据

4.ws.onclose = function(evt) { console.log(“WebSocketClosed!”); };
当客户端收到服务端发送的关闭连接的请求时,触发onclose事件

5.ws.onerror = function(evt) { console.log(“WebSocketError!”); };
如果出现连接,处理,接收,发送数据失败的时候就会触发onerror事件


二、服务端
第一个用于处理websocket请求
第一个类
public class SocketServer extends WebSocketServlet {
    private static final long serialVersionUID = 1L;
    //……
    @Override
    protected StreamInbound createWebSocketInbound(String arg0,
            HttpServletRequest arg1) {
        // TODO Auto-generated method stub
        return new ChatWebSocket(users);
    }
}

这个Servlet继承自WebSocketServlet,实现createWebSocketInbound方法。该方法返回第二个类的实例。

第二个用于处理每一次具体的WebSocket任务
protected void onTextMessage(CharBuffer message) throws IOException { }
文本消息响应
protected void onBinaryMessage(ByteBuffer arg0) throws IOException { }
二进制消息响应
protected void onOpen(WsOutbound outbound) { }
建立连接的触发的事件
protected void onClose(int status) { }
关闭连接时触发的事件



客户端代码
/opt/apache-tomcat-7.0.62/webapps/websocket
<!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>Insert title here</title>      
</head>  
<script type="text/javascript">      
    var ws = null;    
    function log(text) {    
       document.getElementById("log").innerHTML = text +'\n'+document.getElementById("log").innerHTML;    
    }      
    function startServer() {      
      //  var url = document.getElementById("serverip").value;// "ws://192.168.0.102:8887"; 
        var url ="ws://192.168.137.29:8088/websocket/websocket/test";
        if ('WebSocket' in window) {      
            ws = new WebSocket(url);      
        } else if ('MozWebSocket' in window) {      
            ws = new MozWebSocket(url);      
        } else {      
            alert('浏览器不支持');      
            return;    
        }      
        ws.onopen = function() {      
            alert('Opened!');      
        };      
        // 收到服务器发送的文本消息, event.data表示文本内容      
        ws.onmessage = function(event) {      
            alert('Receive message: ' + event.data);     
            log('Receive message: ' + event.data);     
        };      
        ws.onclose = function() {      
          alert('Closed!');      
        };      
        
    }



服务端代码
package testwebsocket;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.ArrayList;  
import javax.servlet.http.HttpServletRequest;  
import org.apache.catalina.websocket.MessageInbound;  
import org.apache.catalina.websocket.StreamInbound;  
import org.apache.catalina.websocket.WebSocketServlet;  
import org.apache.catalina.websocket.WsOutbound;  
  
public class HelloWorldWebSocketServlet extends WebSocketServlet {  
    private static ArrayList mmiList  = new ArrayList();  
  
    protected StreamInbound createWebSocketInbound(String subProtocol,  
            HttpServletRequest arg1) {  
        return new MyMessageInbound();  
    }  
  
    private class MyMessageInbound extends MessageInbound {  
        WsOutbound myoutbound;  
  
        @Override  
        public void onOpen(WsOutbound outbound) {  
            try {  
                System.out.println("Open Client.");  
                this.myoutbound = outbound;  
            //    mmiList .add(this);  
                outbound.writeTextMessage(CharBuffer.wrap("Hello!"));  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
  
        @Override  
        public void onClose(int status) {  
            System.out.println("Close Client.");  
           // mmiList .remove(this);  
        }  
  
        @Override  
        protected void onBinaryMessage(ByteBuffer arg0) throws IOException {  
            // TODO Auto-generated method stub    
  
        }  
  
        @Override  
        protected void onTextMessage(CharBuffer message) throws IOException {  
            // TODO Auto-generated method stub    
            System.out.println("onText--->" + message.toString());  
         //   MyMessageInbound mmib = (MyMessageInbound) outbound;  
            CharBuffer buffer = CharBuffer.wrap(message);  
            System.out.println("onText---ssss>" + message.toString());
            myoutbound.writeTextMessage(buffer);  
            System.out.println("onText---dddd>" + message.toString());
            myoutbound.flush();   
  
        }  
    }  
}





完整的web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0"
  metadata-complete="true">

  <display-name>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tomcat
  </description>

  <servlet>  
      <servlet-name>hello</servlet-name>  
      <servlet-class>com.HelloWorldWebSocketServlet</servlet-class>  
    </servlet>  
    <servlet-mapping>  
      <servlet-name>hello</servlet-name>  
      <url-pattern>/websocket/test</url-pattern>  
    </servlet-mapping>
</web-app>

分享到:
评论

相关推荐

    基于WebAssembly和WebSocket的前端播放器

    基于WebAssembly和WebSocket的前端播放器 通过WebSocket协议,将视频流从回调函数取出通过Wasm解码在前端播放 WebSocket客户端文件夹是参考资料,可看可不看(感兴趣的可以瞅一眼)。 JSWebSocket文件夹中是完整的...

    详解微信小程序实现WebSocket心跳重连

    最近在开发小程序用到了WebSocket,小程序提供了相应的原生API,与H5的API使用方式上有一些区别,所以流行的H5的一些成熟的类库使用起来有些困难,而原生API又存在一些缺陷,所以就自己实现了一套心跳重连机制。...

    javax.websocket-api-1.1-API文档-中文版.zip

    赠送jar包:javax.websocket-api-1.1.jar; 赠送原API文档:javax.websocket-api-1.1-javadoc.jar; 赠送源代码:javax.websocket-api-1.1-sources.jar; 赠送Maven依赖信息文件:javax.websocket-api-1.1.pom; ...

    jakarta.websocket-api-1.1.2-API文档-中文版.zip

    赠送jar包:jakarta.websocket-api-1.1.2.jar; 赠送原API文档:jakarta.websocket-api-1.1.2-javadoc.jar; 赠送源代码:jakarta.websocket-api-1.1.2-sources.jar; 赠送Maven依赖信息文件:jakarta.websocket-api...

    websocket-api-9.4.11.v20180605-API文档-中文版.zip

    赠送jar包:websocket-api-9.4.11.v20180605.jar; 赠送原API文档:websocket-api-9.4.11.v20180605-javadoc.jar; 赠送源代码:websocket-api-9.4.11.v20180605-sources.jar; 赠送Maven依赖信息文件:websocket-...

    jakarta.websocket-api-1.1.2-API文档-中英对照版.zip

    赠送jar包:jakarta.websocket-api-1.1.2.jar; 赠送原API文档:jakarta.websocket-api-1.1.2-javadoc.jar; 赠送源代码:jakarta.websocket-api-1.1.2-sources.jar; 赠送Maven依赖信息文件:jakarta.websocket-api...

    微信小程序webSocket的使用方法

    本篇博客介绍微信小程序中webSocket的使用方法,以及如何用局部网络建立webSocket连接,进行客户端与服务器之间的对话: webSocket简介 微信小程序端API调用 服务器端使用nodejs配置 演示websocket webSocket...

    Android WebSocket实现即时通讯功能

    使用Java-WebSocket开源框架开发Android端即时通讯功能。主要功能: 1、与websocket建立长连接 2、与websocket进行即时通讯 3、Service和Activity之间通讯和UI更新 4、弹出消息通知(包括锁屏通知) 5、心跳检测和重...

    jmeter4.0加插件websocket包,共7个,完整

    可用于 websocket接口测试! Jmeter的WebSocket协议支持插件: JMeterWebSocketSampler-1.0.2-SNAPSHOT.jar 所需依赖包: 1、jetty-http-9.1.2.v20140210.jar 2、jetty-io-9.1.2.v20140210.jar 3、jetty-util-9.1.2....

    java-websocket-1.3.0.jar

    websocket

    java开发基于SpringBoot+WebSocket+Redis分布式即时通讯群聊系统.zip

    Java开发基于SpringBoot+WebSocket+Redis分布式即时通讯群聊系统。一个基于Spring Boot + WebSocket + Redis,可快速开发的分布式即时通讯群聊系统。适用于直播间聊天、游戏内聊天、客服聊天等临时性群聊场景。 ...

    websocket-cluster:这是一个针对WebSocket集群服务器的Spring Cloud项目。

    实战Spring Cloud的WebSocket体现此项目是一个WebSocket实施的实践,基于Spring Cloud。原理我们利用一致性哈希算法,构造一个哈希环,网关监听WebSocket服务实例的上下线消息,根据实例的变化动态地更新哈希环。将...

    DelphiWebsockets-master.zip_delphi websocket_websocket_websocket

    WebSocket for Delphi

    websocket实现前后台数据更新

    1、前端页面 ... 2、javascript websocket.js,websocket页面使用javascript...WebSocketServer.java、WebSocketConfig.java 定义后台onopen、onmessage、onclose、onerror函数及信息发送函数,提供给websoceket功能支持。

    一个简单的网页 Websocket 连接并实现心跳 Heartbeat

    let ws = new WebSocket('wss://echo.websocket.org/'); 然后是通过回调函数获取服务器消息以及对连接状态进行捕捉。 // 成功连接时触发 ws.onopen = () =&gt; { console.log('连接成功.'); this.send('{event:...

    websocket_for_linux-master_websocket_websocket客户端_WEBSOCKET单片机实现

    5WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。...

    基于node+vue实现简单的WebSocket聊天功能

    首先,我需要用到node的nodejs-websocket模块 使用yarn进行安装 yarn add nodejs-websocket –save 当然,你也可以用npm进行安装 npm i nodejs-websocket –save 安装完毕之后,我们开始写服务端的代码,首先,...

    Uniapp使用GoEasy实现websocket实时通讯

    Uniapp作为近来最火的移动端开发技术,一套代码,可以打包成Android/iOS app和各种平台的小程序,可谓是没有最方便只有更方便。 GoEasy上架DCloud Uniapp...Uniapp官方的websocket API主要是用来与您的websocket服务

    Android 实现WebSocket长连接

    Android 实现WebSocket长连接 最近项目中引入了实时接收服务器数据的功能,考量后通过WebSocket长链接来实现。 1、建立在 TCP 协议之上,服务器端的实现比较容易。 2、与 HTTP 协议有着良好的兼容性。默认端口也是80...

    python实现WebSocket服务端过程解析

    一种类似Flask开发的WebSocket-Server服务端框架,适用python3.X 1、安装模块Pywss pip install pywss 2、搭建简易服务器 2.1 服务端代码 代码简介 route: 注册请求路径 example_1(request, data): request: ...

Global site tag (gtag.js) - Google Analytics