websocket使用小例子

3 篇文章 0 订阅
1、后台代码Websocket.java
package com.sinosoft.tyoa.websocket;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

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;

@ServerEndpoint("/websocket")
public class Websocket {

private static Map<String,Session> sessionMap = new Hashtable<String,Session>();


@OnMessage
public void onMessage(String message, Session currentSession) {


/*// Send the message to the client
Set<Map.Entry<String,Session>> set = sessionMap.entrySet();
for (Map.Entry<String,Session> session: set) {
if(session.getValue().isOpen() == true) {
try {
System.out.println(session.getValue());
session.getValue().getBasicRemote().sendText(message);
} catch (IOException e) {
sessionMap.remove(session.getValue());
//e.printStackTrace();
}
}
else {
System.out.println("close:"+session.getValue());
sessionMap.remove(session.getValue());
}
}*/

//服务器往各个客户端发送消息
Iterator<String> iterator = sessionMap.keySet().iterator();
while(iterator.hasNext()) {
String key = (String) iterator.next();
Session session = sessionMap.get(key);
if(session.isOpen() == true) {
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
iterator.remove();
sessionMap.remove(key);
//e.printStackTrace();
}
}
else {
iterator.remove();
sessionMap.remove(key);
}
}
}

@OnOpen
public void onOpen(Session currentSession) {
if(sessionMap.containsValue(currentSession) == false){
sessionMap.put(currentSession.getId(), currentSession);
}
//System.out.println("Client connected");
}

@OnClose
public void onClose(Session currentSession) throws IOException{
sessionMap.remove(currentSession.getId());
//System.out.println("Client closed");
}

@OnError
public void onClose(Session currentSession,java.lang.Throwable throwable) throws IOException{
sessionMap.remove(currentSession.getId());
//System.out.println("Client closed");
}
}


2、pom.xml文件配置
    <!-- websocket -->
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
<!-- websocket end -->

3、前台页面
<%@ page language="java" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = "ws" + "://"+ request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<script type="text/javascript">
var wsURI = "<%=basePath%>websocket";
var websocket = null;

function connectWebSocket(wsURI) {
if(websocket == null) {
websocket = new WebSocket(wsURI);
websocket.onopen = function(openEvent) {
$("#showMsg").append("连接成功...<br/>");
};
websocket.onclose = function(closeEvent) {
websocket == null;
$("#showMsg").append("关闭连接成功...<br/>");
};
websocket.onmessage = function(messageEvent) {
$("#showMsg").append("<span style='display:block'>" + messageEvent.data + "</span>");
};
websocket.onerror = function(errorEvent) {
//alert(errorEvent.data);
};
}
}

function sendMessageToClient(message) {
websocket.send(message);
}


$("#sendButton").click(function() {
sendMessageToClient($("#msg").val());
$("#msg").val("");
});


$(function(){
if(!("WebSocket" in window)){
alert("浏览器不支持!");
}
else {
connectWebSocket(wsURI);
}
});
</script>
<body>
<div id="showMsg" style="border: 1px solid; width: 500px; height: 400px; overflow: auto;"></div>
<div>
<input type="text" id="msg" />
<input type="button" id="sendButton" value="发送" />
</div>
</body>




3、[color=red]出现错误可能原因:项目有拦截器,把/webscoket添加到可访问路径;jar包配置问题,tomcat7有支持jar包,所有pom.xml里面要依赖jar包要设置编译需要而发布不需要。[/color]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值