是不是我哪里配置有问题?
从网上直接复制的答案,甚至是直接下载的demo,死活连接不上。
在myeclipse里面跑的,用的是myeclipse自带的tomcat 8.5 javaee是1.7 javase是1.8
前端 <%@ page language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Java后端WebSocket的Tomcat实现</title>
</head>
<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;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://127.0.0.1:8080/websocket");
}
else {
alert('当前浏览器 Not support websocket')
} //连接发生错误的回调方法
websocket.onerror = function () {
setMessageInnerHTML("WebSocket连接发生错误");
setMessageInnerHTML(websocket.url);
}; //连接成功建立的回调方法
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>
</html>
package testwebsockt;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import net.sf.json.JSONObject;
@ServerEndpoint("/websocket")
public class websocket {
private static int onlineCount = 0;
private static Map<String, websocket> clients = new ConcurrentHashMap<String, websocket>();
private Session session;
private String username;
@OnOpen
public void onOpen(@PathParam("username") String username, Session session) throws IOException {
this.username = username;
this.session = session;
addOnlineCount();
clients.put(username, this);
System.out.println("已连接");
}
@OnClose
public void onClose() throws IOException {
clients.remove(username);
subOnlineCount();
}
@OnMessage
public void onMessage(String message) throws IOException {
JSONObject jsonTo = JSONObject.fromObject(message);
if (!jsonTo.get("To").equals("All")){
sendMessageTo("给一个人", jsonTo.get("To").toString());
}else{
sendMessageAll("给所有人");
}
}
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
public void sendMessageTo(String message, String To) throws IOException {
// session.getBasicRemote().sendText(message);
//session.getAsyncRemote().sendText(message);
for (websocket item : clients.values()) {
if (item.username.equals(To) )
item.session.getAsyncRemote().sendText(message);
}
}
public void sendMessageAll(String message) throws IOException {
for (websocket item : clients.values()) {
item.session.getAsyncRemote().sendText(message);
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
websocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
websocket.onlineCount--;
}
public static synchronized Map<String, websocket> getClients() {
return clients;
}
}
这段代码都是直接从网上抄的,但就是连不上,始终都在触发onerr那个事件
从网上直接复制的答案,甚至是直接下载的demo,死活连接不上。
在myeclipse里面跑的,用的是myeclipse自带的tomcat 8.5 javaee是1.7 javase是1.8
前端 <%@ page language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Java后端WebSocket的Tomcat实现</title>
</head>
<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;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://127.0.0.1:8080/websocket");
}
else {
alert('当前浏览器 Not support websocket')
} //连接发生错误的回调方法
websocket.onerror = function () {
setMessageInnerHTML("WebSocket连接发生错误");
setMessageInnerHTML(websocket.url);
}; //连接成功建立的回调方法
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>
</html>
package testwebsockt;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import net.sf.json.JSONObject;
@ServerEndpoint("/websocket")
public class websocket {
private static int onlineCount = 0;
private static Map<String, websocket> clients = new ConcurrentHashMap<String, websocket>();
private Session session;
private String username;
@OnOpen
public void onOpen(@PathParam("username") String username, Session session) throws IOException {
this.username = username;
this.session = session;
addOnlineCount();
clients.put(username, this);
System.out.println("已连接");
}
@OnClose
public void onClose() throws IOException {
clients.remove(username);
subOnlineCount();
}
@OnMessage
public void onMessage(String message) throws IOException {
JSONObject jsonTo = JSONObject.fromObject(message);
if (!jsonTo.get("To").equals("All")){
sendMessageTo("给一个人", jsonTo.get("To").toString());
}else{
sendMessageAll("给所有人");
}
}
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
public void sendMessageTo(String message, String To) throws IOException {
// session.getBasicRemote().sendText(message);
//session.getAsyncRemote().sendText(message);
for (websocket item : clients.values()) {
if (item.username.equals(To) )
item.session.getAsyncRemote().sendText(message);
}
}
public void sendMessageAll(String message) throws IOException {
for (websocket item : clients.values()) {
item.session.getAsyncRemote().sendText(message);
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
websocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
websocket.onlineCount--;
}
public static synchronized Map<String, websocket> getClients() {
return clients;
}
}
这段代码都是直接从网上抄的,但就是连不上,始终都在触发onerr那个事件
解决方案 »
- 求一份覃庆炎//张伟的 Java开源项目:Spring+Hibernate+Struts项目开发详解 的随书光盘或者电子书...
- 打开index.jsp页面的时候同时加载iframe中内容的问题
- Acegi 问题
- 拆分字符
- birt报表记录出现重复记录
- 请教一个问题。求高手帮忙。
- 在Struts2中使用struts-menu做动态菜单的问题!
- STRUTS1.1中用<html:errors/>,中文不能正确显示?
- org.springframework.beans.factory.BeanCreationException异常
- SpringCloud集成ribbon启动失败
- 有用过jeeSite做过项目的人吗?请教下使用开源的代码,不需要服务,也要购买许可吗?
- spring boot 集成dubbo启动异常
websocket = new WebSocket("ws://127.0.0.1:8080/websocket");仔细检查下上面的地址,连不上应该就是url写错了,是不是漏掉项目名,或者端口错误之类。
我之前也试过网上的例子,可以发消息。
写成动态的不怕错
var url = "${pageContext.request.getServerName()}:"
+"${pageContext.request.getServerPort()}"
+"${pageContext.request.contextPath}/websocket";
//聊天服务
var socket = new WebSocket("ws://" + url);