websocket
2015-11-27 11:46
225 查看
服务端
WebsocketTest.java[code] package com.ws.test; import java.io.IOException; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; @ServerEndpoint("/websocket") public class WebSocketTest { @OnMessage public void onMessage(String message, Session session)throws IOException, InterruptedException { System.out.println("Received: " + message); // Send the first message to the client session.getBasicRemote().sendText("This is the first server message"); // Send 3 messages to the client every 5 seconds int sentMessages = 0; while(sentMessages < 3){ Thread.sleep(5000); session.getBasicRemote(). sendText("This is an intermediate server message. Count: " + sentMessages); sentMessages++; } // Send a final message to the client session.getBasicRemote().sendText("This is the last server message"); } @OnOpen public void onOpen() { System.out.println("Client connected"); } @OnClose public void onClose() { System.out.println("Connection closed"); } }
客户端
index.jsp[code]<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <div> <input type="submit" value="Start" onclick="oprate(23,111)" /> </div> <div id="messages"></div> <script type="text/javascript"> function json2str(o) { var arr = []; var fmt = function(s) { if (typeof s == 'object' && s != null) return json2str(s); return /^(string|number)$/.test(typeof s) ? "'" + s + "'" : s; } for ( var i in o) arr.push("'" + i + "':" + fmt(o[i])); return '{' + arr.join(',') + '}'; }; function WebSocketTest(keyid, openid) { if ("WebSocket" in window) { var count = 0; var ws = new WebSocket('ws://localhost:8080/websocket/websocket'); ws.onopen = function() { var obj = { deviceMessage : { "value" : keyid, "command" : "ir" "userid" : openid, "time" : new Date().getTime(), } }; ws.send(json2str(obj)); }; ws.onmessage = function(evt) { var received_msg = evt.data;//alert("Message is received..." + received_msg); }; } else { //DO } }; function oprate(keyid, openid) { WebSocketTest(keyid, openid); } </script> </body> </html>
相关文章推荐
- 享元模式
- Linux中将网络管理器由NetworkManager切换为systemd-network
- win10输入法切换不了怎么办?win10无法切换输入法现象的解决方法
- OPENCV249 编译静态库(含CUDA,OPENCL)
- C语言编程优化运行速度
- IOS技术调研
- SQL笔记(5)_第五章 操作数据
- Pycharm5注册方式
- 关于“创业者与VC见面的10个不成文细节点”
- Ubuntu关闭图形界面
- 定时且周期性的任务研究I--Timer
- ASP.NET repeater添加序号列的方法
- [基础] - Python中的@property
- 培训机构毕业的程序员被歧视的背后逻辑
- 解决webstorm本地IP访问页面出错的问题
- 微信公众号开发
- goke 交叉编译gdb
- AndroidL 源码编译 预置GMS包与第三方应用 系统属性管理
- mybatis中的resultMap
- 用C语言获取任意文件的长度(可能大于2GB)#define _FILE_OFFSET_BITS 64