HTML5 WebSocket完成点对点闲聊的示例编码

日期:2021-02-23 类型:科技新闻 

关键词:网页设计,移动端网页设计,大一网页设计作业成品,网页编辑软件,网页在线编辑

昨日应用HTML5的websocket与Tomcat完成了多人闲聊,那是最简易也是最基础的,在其中留意的便是开发设计自然环境,要考虑jdk1.7和tomcat8,自然了tom7 的7.063也行!

今日是国庆的最终1天,苦逼的加班,再次搞编码!让人高兴的是,我用google寻找了有关websocket的点对点闲聊,更好的是能够和大多数数系统软件很好的相互配合起看来下实际效果图

由于是仿真模拟的,这里得出的是两个JSP网页页面A和B,里边各自向session里放了两个姓名小明和小化,留意,这里的session是HttpSession session,以前多人闲聊里的session是javax.websocket.Session;不1样的。

这里想1下, 应用HttpSession session操纵闲聊的客户,益处如何,自身猜~~~

这里沒有应用注释,传统式的web.xml配备方法,最先在系统软件起动的情况下启用InitServlet方式

public class InitServlet extends HttpServlet {
    private static final long serialVersionUID = ⑶1759907L;  
    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⑻"?>
<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中解决前台接待传出的信息内容,并封裝信息内容发送给总体目标

也有1个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⑻"
    pageEncoding="UTF⑻"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF⑻">
<title>Index</title>
<script type="text/javascript" src="js/jquery⑴.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>
闲聊框:<div id="message" style="height: 250px;width: 280px;border: 1px solid; overflow: auto;"></div>
<br>
<input type="button" value="send" onclick="sendMsg()"></input>
</body>
</html>

这是A.jsp网页页面,B同上

根据以上编码,便可以完成1个点对点的闲聊作用,假如做的大,能够做成1个web版的闲聊系统软件,包含闲聊室和单人闲聊,都说websocket不适用2进制的传送,可是看到个大流说了这样的话

但是如今做下来 觉得应用2进制的实际意义并不是很大。很久之前就1直困混,如何都说JS不适用2进制,发现实际上只是1堆坑货对这个没科学研究。。(用的是filereader)

以上便是本文的所有內容,期待对大伙儿的学习培训有一定的协助,也期待大伙儿多多适用脚本制作之家。