websocket实现方式
2019独角兽企业重金招聘Python工程师标准>>>
一、jetty9、tomcat7 + html5
1、server---pom.xml:
<!-- j2ee --><dependency><groupId>javax</groupId><artifactId>javaee-api</artifactId><version>7.0</version><scope>provided</scope></dependency>
2、server---java代码:
package com.bluedon.websocket;
import java.io.IOException;
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.ServerEndpoint;
//该注解用来指定一个URI,客户端可以通过这个URI来连接到WebSocket。类似Servlet的注解mapping。无需在web.xml中配置。
@ServerEndpoint("/webSocketServer")
public class WebSocketServer {//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。private static int onlineCount = 0;//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();//与某个客户端的连接会话,需要通过它来给客户端发送数据private Session session;/*** 连接建立成功调用的方法* @param session 可的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据*/@OnOpenpublic void onOpen(Session session){this.session = session;webSocketSet.add(this); //加入set中addOnlineCount(); //在线数加1System.out.println("新连接加入!当前在线人数为" + getOnlineCount());}/*** 连接关闭调用的方法*/@OnClosepublic void onClose(){webSocketSet.remove(this); //从set中删除subOnlineCount(); //在线数减1 System.out.println("一连接关闭!当前在线人数为" + getOnlineCount());}/*** 收到客户端消息后调用的方法* @param message 客户端发送过来的消息* @param session 可的参数*/@OnMessagepublic void onMessage(String message, Session session) {System.out.println("来自客户端的消息:" + message);//群发消息for(WebSocketServer item: webSocketSet){ try {item.sendMessage(message);} catch (IOException e) {e.printStackTrace();continue;}}}/*** 发生错误时调用* @param session* @param error*/@OnErrorpublic void onError(Session session, Throwable error){System.out.println("发生错误");//error.printStackTrace();}/*** 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。* @param message* @throws IOException*/public void sendMessage(String message) throws IOException{this.session.getBasicRemote().sendText(message);//this.session.getAsyncRemote().sendText(message);}public static synchronized int getOnlineCount() {return onlineCount;}public static synchronized void addOnlineCount() {WebSocketServer.onlineCount++;}public static synchronized void subOnlineCount() {WebSocketServer.onlineCount--;}
}
3、html5:
<body>Welcome<br/><input id="text" type="text"/><button onclick="send()">发送消息</button><hr/><button onclick="closeWebSocket()">关闭WebSocket连接</button><hr/><div id="message"></div>
</body><script type="text/javascript">var websocket = null;//判断当前浏览器是否支持WebSocketif ('WebSocket' in window) {websocket = new WebSocket("ws://localhost:8080/websocket/webSocketServer");}else {alert('当前浏览器 Not support websocket')}//连接发生错误的回调方法websocket.onerror = function (e) {setMessageInnerHTML("WebSocket连接发生错误");};//连接成功建立的回调方法websocket.onopen = function () {setMessageInnerHTML("WebSocket连接成功");}//接收到消息的回调方法websocket.onmessage = function (event) {setMessageInnerHTML(event.data);}//连接关闭的回调方法websocket.onclose = function () {setMessageInnerHTML("WebSocket连接关闭");}//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。window.onbeforeunload = function () {closeWebSocket();}//将消息显示在网页上function setMessageInnerHTML(innerHTML) {document.getElementById('message').innerHTML += innerHTML + '<br/>';}//关闭WebSocket连接function closeWebSocket() {websocket.close();}//发送消息function send() {var message = document.getElementById('text').value;websocket.send(message);}
</script>
二、jetty9、tomcat7 + 客户端
1、服务端同上
2、客户端
pom.xml:
<dependency><groupId>org.glassfish.tyrus.bundles</groupId><artifactId>tyrus-standalone-client</artifactId><version>1.13</version></dependency>或者<dependency><groupId>org.glassfish.tyrus</groupId><artifactId>tyrus-client</artifactId><version>1.1</version></dependency><dependency><groupId>org.glassfish.tyrus</groupId><artifactId>tyrus-container-grizzly</artifactId><version>1.1</version></dependency>
代码:
public class test {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubt1();}public static void t1() {WebsocketClient c = new WebsocketClient();WebsocketClient.connect(c, "ws://localhost:8088/websockets/webSocketServer");c.sendUserInfo("测试");try {Thread.sleep(100000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}
}
@ClientEndpoint
public class WebsocketClient {private Session session;@OnOpenpublic void init(Session session) {this.session = session;}@OnMessagepublic void onMessage(String userInfo) {System.out.println("client receiver String " + userInfo);}@OnErrorpublic void handleError(Throwable thw) {if (thw instanceof DecodeException) {Logger.getLogger("lwl").info(session.getId() + " Error decoding incoming message: " + ((DecodeException) thw).getText());} else {Logger.getLogger("lwl").info(session.getId() + " Client WebSocket error: " + thw.getMessage());}}/*** 建立于服务端的连接* * @param client* @param path* @return*/public static Session connect(WebsocketClient clientEndpoint, String path) {WebSocketContainer wsc = ContainerProvider.getWebSocketContainer();try {return wsc.connectToServer(clientEndpoint, new URI(path));} catch (Exception e) {e.printStackTrace();}return null;}/*** 向服务端发送数据* * @param userInfo*/public void sendUserInfo(String text) {try {this.session.getBasicRemote().sendText(text);} catch (IOException e) {e.printStackTrace();}}/*** 断开与服务端的连接*/public void disconnect() {if (this.session != null) {try {this.session.close();} catch (IOException ioe) {System.out.println("Error closing the session: " + ioe);}}}
}
三、客户端+服务端(不依赖与tomcat和jetty)
1、客户端pom.xml、代码同(二)
2、服务端
pom.xml:
<dependency><groupId>org.glassfish.tyrus</groupId><artifactId>tyrus-server</artifactId><version>1.1</version></dependency><dependency><groupId>org.glassfish.tyrus</groupId><artifactId>tyrus-container-grizzly</artifactId><version>1.1</version></dependency>
代码:
public class WebSocketServerStatic {public static void main(String[] args) {runServer();}public static void runServer() {Server server = new Server("localhost", 8080, "/websocket", WebSocketServer.class);try {server.start();Thread.currentThread().join();} catch (Exception e) {throw new RuntimeException(e);} finally {}}
}
@ServerEndpoint("/webSocketServer")
public class WebSocketServer {//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。private static int onlineCount = 0;//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();//与某个客户端的连接会话,需要通过它来给客户端发送数据private Session session;/*** 连接建立成功调用的方法* @param session 可的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据*/@OnOpenpublic void onOpen(Session session){this.session = session;webSocketSet.add(this); //加入set中addOnlineCount(); //在线数加1System.out.println("新连接加入!当前在线人数为" + getOnlineCount());}/*** 连接关闭调用的方法*/@OnClosepublic void onClose(){webSocketSet.remove(this); //从set中删除subOnlineCount(); //在线数减1 System.out.println("一连接关闭!当前在线人数为" + getOnlineCount());}/*** 收到客户端消息后调用的方法* @param message 客户端发送过来的消息* @param session 可的参数*/@OnMessagepublic void onMessage(String message, Session session) {System.out.println("来自客户端的消息:" + message);//群发消息for(WebSocketServer item: webSocketSet){ try {item.sendMessage(message);} catch (IOException e) {e.printStackTrace();continue;}}}/*** 发生错误时调用* @param session* @param error*/@OnErrorpublic void onError(Session session, Throwable error){System.out.println("发生错误");//error.printStackTrace();}/*** 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。* @param message* @throws IOException*/public void sendMessage(String message) throws IOException{this.session.getBasicRemote().sendText(message);//this.session.getAsyncRemote().sendText(message);}public static synchronized int getOnlineCount() {return onlineCount;}public static synchronized void addOnlineCount() {WebSocketServer.onlineCount++;}public static synchronized void subOnlineCount() {WebSocketServer.onlineCount--;}
}
转载于:https://my.oschina.net/u/920528/blog/844907
websocket实现方式相关推荐
- WEB消息提醒实现之二 实现方式-websocket实现方式
#websocket实现方式 ##原理 websocket的原理主要是,利用websocket提供的api,客户端只需要向服务器发起一次连接即可,然后服务器就可以主动地源源不断地向客户端发送数据,只要 ...
- 一文搞懂四种 WebSocket 使用方式
在上家公司做IM消息系统的时候,一直是使用 WebSocket 作为收发消息的基础组件,今天就和大家聊聊在 Java 中,使用 WebSocket 所常见的四种姿势,如果大家以后或者现在碰到有要使用 ...
- C#使用MQTTnet的websocket加密方式(wss)实现MQTTClient
Mqttnet库的功能还是很强大的,可以直接在vs的NuGet里面下载,注意要下载最新版本,有些只有MQTT 的TCP连接方式,因为这个原因我走了很多弯路. 网上使用MQTTnet的库的很多都是TCP ...
- SpringBoot集成websocket(Spring方式)
SpringWebSocketConfig配置 package com.meeno.chemical.socket.task.config;import com.meeno.chemical.sock ...
- java 实现websocket的两种方式
简单说明 1.两种方式,一种使用tomcat的websocket实现,一种使用spring的websocket 2.tomcat的方式需要tomcat 7.x,JEE7的支持. 3.spring与we ...
- 基于 springBoot 实现webSocket方式的扫码登录
最近单位又有一个新Java项目. 涉及到扫码登录.之前项目使用的是 ajax轮询的方式.感觉太low了. 所以这次用webSocket的方式进行实现 好.废话不多说!咱们开始!! 一.首先咱们需要一张 ...
- 物联网协议对比(HTTP、websocket、XMPP、COAP、MQTT和DDS协议)
目录 1.HTTP和websocket 2.XMPP 3.COAP 4.MQTT协议 5.DDS 对于物联网,最重要的是在互联网中设备与设备的通讯,现在物联网在internet通信中比较常见的通讯协议 ...
- https协议必须使用443端口吗_http、https、http2、websocket之间的关系
http.https.http2.websocket之间的关系 http:目前绝大多数是http1.1版本,最原始的web协议,默认80端口,基于TCP协议. https:加密的http协议,默认44 ...
- WebSocket的故事(六)—— Springboot中,实现更灵活的WebSocket
概述 WebSocket的故事系列计划分五大篇六章,旨在由浅入深的介绍WebSocket以及在Springboot中如何快速构建和使用WebSocket提供的能力.本系列计划包含如下几篇文章: 第一篇 ...
最新文章
- python用for循环一直出现最后一个值_python中for循环的list最后一个数据总会覆盖前面的数据...
- 使用JAXP对xml文档进行DOM解析基础
- left edge algorithm.
- java布尔类型比较器_Java 8比较器类型推论非常困惑
- how to build a paper's architecture?
- (百度、谷歌)地图经纬度gps偏移解决办法:gps纠偏数据库纠偏
- 移动端使用页尾文字使用绝对定位遇到input框会飘起来的处理方案
- Mesos容器引擎的架构设计和实现解析
- python 使用异常函数_您如何测试Python函数引发异常?
- malloc动态分配数组以及指针数组大小
- 2017.8.10 奖励关 思考记录
- PSIM软件学习---07 元件参数动态扫描
- Git合并两个远程代码库
- luogu P3332 [ZJOI2013]K大数查询
- repost 从APP工厂到游戏工厂?字节跳动进攻腾讯腹地
- win7计算机ip地址怎么查,win7电脑的IP地址怎样查看
- js仿苹果风格弹出框alert插件
- MySQL的错误1264, 1406, 1329 ,1101 的修改方法
- 人机交互-7-交互需求定义
- Python图像增强之高斯模糊、中值模糊、均值模糊