发布网友 发布时间:2022-04-23 08:02
共2个回答
懂视网 时间:2022-04-20 04:54
昨天使用HTML5的websocket与Tomcat实现了多人聊天,那是最简单也是最基本的,其中注意的就是开发环境,要满足jdk1.7和tomcat8,当然了tom7 的7.063也行!
本文主要和大家介绍HTML5 WebSocket实现点对点聊天的示例代码的相关资料,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧,希望能帮助到大家。
因为是模拟的,这里给出的是两个JSP页面A和B,里面分别向session里放了两个名字小明和小化,注意,这里的session是HttpSession session,之前多人聊天里的session是javax.websocket.Session;不一样的。
这里想一下, 使用HttpSession session控制聊天的用户,好处怎样,自己猜~~~
这里没有使用注解,传统的web.xml配置方式,首先在系统启动的时候调用InitServlet方法
public class InitServlet extends HttpServlet { private static final long serialVersionUID = -3163557381361759907L; private static HashMap<String,MessageInbound> socketList; public void init(ServletConfig config) throws ServletException { InitServlet.socketList = new HashMap<String,MessageInbound>(); super.init(config); System.out.println("初始化聊天容器"); } public static HashMap<String,MessageInbound> getSocketList() { return InitServlet.socketList; } }
这里你可以跟自己的系统结合,对应的web配置代码如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" 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"> <servlet> <servlet-name>websocket</servlet-name> <servlet-class>socket.MyWebSocketServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>websocket</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <servlet> <servlet-name>initServlet</servlet-name> <servlet-class>socket.InitServlet</servlet-class> <load-on-startup>1</load-on-startup><!--方法执行的级别--> </servlet> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
这就是最普通的前台像后台发送请求的过程,也是很容易嵌入到自己的系统里
MyWebSocketServlet:
public class MyWebSocketServlet extends WebSocketServlet { public String getUser(HttpServletRequest request){ String userName = (String) request.getSession().getAttribute("user"); if(userName==null){ return null; } return userName; } protected StreamInbound createWebSocketInbound(String arg0, HttpServletRequest request) { System.out.println("用户" + request.getSession().getAttribute("user") + "登录"); return new MyMessageInbound(this.getUser(request)); } }
MyMessageInbound继承MessageInbound
package socket; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.util.HashMap; import org.apache.catalina.websocket.MessageInbound; import org.apache.catalina.websocket.WsOutbound; import util.MessageUtil; public class MyMessageInbound extends MessageInbound { private String name; public MyMessageInbound() { super(); } public MyMessageInbound(String name) { super(); this.name = name; } @Override protected void onBinaryMessage(ByteBuffer arg0) throws IOException { } @Override protected void onTextMessage(CharBuffer msg) throws IOException { //用户所发消息处理后的map HashMap<String,String> messageMap = MessageUtil.getMessage(msg); //处理消息类 //上线用户集合类map HashMap<String, MessageInbound> userMsgMap = InitServlet.getSocketList(); String fromName = messageMap.get("fromName"); //消息来自人 的userId String toName = messageMap.get("toName"); //消息发往人的 userId //获取该用户 MessageInbound messageInbound = userMsgMap.get(toName); //在仓库中取出发往人的MessageInbound MessageInbound messageFromInbound = userMsgMap.get(fromName); if(messageInbound!=null && messageFromInbound!=null){ //如果发往人 存在进行操作 WsOutbound outbound = messageInbound.getWsOutbound(); WsOutbound outFromBound = messageFromInbound.getWsOutbound(); String content = messageMap.get("content"); //获取消息内容 String msgContentString = fromName + "说: " + content; //构造发送的消息 //发出去内容 CharBuffer toMsg = CharBuffer.wrap(msgContentString.toCharArray()); CharBuffer fromMsg = CharBuffer.wrap(msgContentString.toCharArray()); outFromBound.writeTextMessage(fromMsg); outbound.writeTextMessage(toMsg); // outFromBound.flush(); outbound.flush(); } } @Override protected void onClose(int status) { InitServlet.getSocketList().remove(this); super.onClose(status); } @Override protected void onOpen(WsOutbound outbound) { super.onOpen(outbound); //登录的用户注册进去 if(name!=null){ InitServlet.getSocketList().put(name, this);//存放客服ID与用户 } } @Override public int getReadTimeout() { return 0; } }
在onTextMessage中处理前台发出的信息,并封装信息传给目标
还有一个messageutil
package util; import java.nio.CharBuffer; import java.util.HashMap; public class MessageUtil { public static HashMap<String,String> getMessage(CharBuffer msg) { HashMap<String,String> map = new HashMap<String,String>(); String msgString = msg.toString(); String m[] = msgString.split(","); map.put("fromName", m[0]); map.put("toName", m[1]); map.put("content", m[2]); return map; } }
当然了,前台也要按照规定的格式传信息
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Index</title> <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script> <%session.setAttribute("user", "小化");%> <script type="text/javascript"> var ws = null; function startWebSocket() { if ('WebSocket' in window) ws = new WebSocket("ws://localhost:8080/WebSocketUser/websocket.do"); else if ('MozWebSocket' in window) ws = new MozWebSocket("ws://localhost:8080/WebSocketUser/websocket.do"); else alert("not support"); ws.onmessage = function(evt) { //alert(evt.data); console.log(evt); // $("#xiaoxi").val(evt.data); setMessageInnerHTML(evt.data); }; function setMessageInnerHTML(innerHTML){ document.getElementById('message').innerHTML += innerHTML + '<br/>'; } ws.onclose = function(evt) { //alert("close"); document.getElementById('denglu').innerHTML="离线"; }; ws.onopen = function(evt) { //alert("open"); document.getElementById('denglu').innerHTML="在线"; document.getElementById('userName').innerHTML='小化'; }; } function sendMsg() { var fromName = "小化"; var toName = document.getElementById('name').value; //发给谁 var content = document.getElementById('writeMsg').value; //发送内容 ws.send(fromName+","+toName+","+content);//注意格式 } </script> </head> <body onload="startWebSocket();"> <p>聊天功能实现</p> 登录状态: <span id="denglu" style="color:red;">正在登录</span> <br> 登录人: <span id="userName"></span> <br> <br> <br> 发送给谁:<input type="text" id="name" value="小明"></input> <br> 发送内容:<input type="text" id="writeMsg"></input> <br> 聊天框:<p id="message" style="height: 250px;width: 280px;border: 1px solid; overflow: auto;"></p> <br> <input type="button" value="send" onclick="sendMsg()"></input> </body> </html>
这是A.jsp页面,B同上
通过以上代码,就可以实现一个点对点的聊天功能,如果做的大,可以做成一个web版的聊天系统,包括聊天室和单人聊天,都说websocket不支持二进制的传输,但是看到个大流说了这样的话
不过现在做下来 感觉使用二进制的意义不是很大。很久以前就一直困混,怎么都说JS不支持二进制,发现其实只是一堆坑货对这个没研究。。(用的是filereader)
热心网友 时间:2022-04-20 02:02
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
var wsServer = 'ws://localhost:9999/webSocket.ashx'; //基于.NET4.5服务器地址
//var wsServer = 'ws://localhost:1818'; //基于.NET服务器地址
var websocket = new WebSocket(wsServer); //创建WebSocket对象
//websocket.send("hello");//向服务器发送消息
//alert(websocket.readyState);//查看websocket当前状态
websocket.onopen = function (evt) {
//已经建立连接
alert("已经建立连接");
};
websocket.onclose = function (evt) {
//已经关闭连接
alert("已经关闭连接");
};
websocket.onmessage = function (evt) {
//收到服务器消息,使用evt.data提取
evt.stopPropagation()
evt.preventDefault()
//alert(evt.data);
writeToScreen(evt.data);
//websocket.close();
};
websocket.onerror = function (evt) {
//产生异常
//alert(evt.message);
writeToScreen(evt.message);
};
function sendMsg() {
if (websocket.readyState == websocket.OPEN) {
msg = document.getElementById("msg").value;
websocket.send(msg);
writeToScreen("发送成功!");
} else {
writeToScreen("连接失败!");
}
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML += message;
output.appendChild(pre);
}
</script>
</head>
<body>
<div>
<input type="text" id="msg" value="beyond is number one!" />
<button onclick="sendMsg()">send</button>
</div>
<div id="output"></div>
</body>
</html>
H5e实训html5开发解答