websocket实现用户双方通信

本文介绍一下websocket的用法,可能介绍的不够专业,所有请见谅了。websocket可以是纯Java实现,也可以整合Maven工程SSM框架实现,前端都是html或jsp的网页进行websocket使用与实现。

我把两种实现方法都说一下,但这两种方法其实大概流程都一样。


纯Java的实现websocket

这是服务器端的代码:

package com.dlnu.man.util;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 * @ServerEndpoint 可以把当前类变成websocket服务类
 */
@ServerEndpoint("/websocket/{userno}")
public class Socket {
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
    private static ConcurrentHashMap<String, Socket> webSocketSet = new ConcurrentHashMap<String, Socket>();
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session WebSocketsession;
    //当前发消息的人员编号
    private String userno = "";

    /**
     * 连接建立成功调用的方法
     *
     * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(@PathParam(value = "userno") String param, Session WebSocketsession, EndpointConfig config) {
        System.out.println(param);
        userno = param;//接收到发送消息的人员编号
        this.WebSocketsession = WebSocketsession;
        webSocketSet.put(param, this);//加入map中
        addOnlineCount();           //在线数加1
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (!userno.equals("")) {
            webSocketSet.remove(userno);  //从set中删除
            subOnlineCount();           //在线数减1
            System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    @SuppressWarnings("unused")
//	@OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
//        session.get
        //群发消息
        if (1 < 2) {
            sendAll(message);
        } else {
            //给指定的人发消息
            sendToUser(message);
        }
    }
    /**
     * 给指定的人发送消息
     * @param message
     */
    @OnMessage
    public void sendToUser(String message) {
        String sendUserno = message.split("[|]")[1];
        String sendMessage = message.split("[|]")[0];
        String now = getNowTime();
        try {
            if (webSocketSet.get(sendUserno) != null) {
                webSocketSet.get(sendUserno).sendMessage(now + "用户" + userno + "发来消息:" + " <br/> " + sendMessage);
            } else {
                System.out.println("当前用户不在线");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 给所有人发消息
     * @param message
     */
    private void sendAll(String message) {
        String now = getNowTime();
        String sendMessage = message.split("[|]")[0];
        //遍历HashMap
        for (String key : webSocketSet.keySet()) {
            try {
                //判断接收用户是否是当前发消息的用户
                if (!userno.equals(key)) {
                    webSocketSet.get(key).sendMessage(now + "用户" + userno + "发来消息:" + " <br/> " + sendMessage);
                    System.out.println("key = " + key);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取当前时间
     *
     * @return
     */
    private String getNowTime() {
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(date);
        return time;
    }
    /**
     * 发生错误时调用
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }
    /**
     * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
     *
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {
        this.WebSocketsession.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
    public static synchronized void addOnlineCount() {
        Socket.onlineCount++;
    }
    public static synchronized void subOnlineCount() {
        Socket.onlineCount--;
    }

下面这是h5的代码,用户登录,实现向数据库传递参数,并返回相应的数据,成功后跳转聊天界面

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>登录页面</title>
		<script type="text/javascript" src="js/jquery.min.js"></script>
		<script type="text/javascript">
			//页面载入完毕后执行,是$(document).ready(function(){});的简写
			$(function(){
				$("#login").click(function(){
					var account=$("#account").val().trim();
					var password=$("#pard").val().trim();
					$.ajax({
						url:"https://utils.top/Mens/Man/login",
						type:"get",
						dataType:"json",
			 			data:{"account":account,"password":password}, 
						success:function(result){
							if(result.status==0){
								window.location.href="soc1.jsp";
							}else{
								 window.location.href="login2.html"; 
								 alert(result.msg); 
							}
						},
						error:function(){
							alert("登录异常");
						}
					});
				}); 
				
			});
</script>

	</head>
	<body>
	<form action="login">
			账户号:<input type="text" id="account"/>
			密码:<input type="password" id="pard"/>
			<button id="login">登录</button>
     </form>
     <br>   <br>   <br>
 
	
	</body>
</html>

上面调用的是写好的登录接口,用的是Swagger工具进行调试API


登录效果图

下面是websocket的页面及其代码

<%@ 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>
 <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0-beta/css/bootstrap.min.css">
  <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://cdn.bootcss.com/popper.js/1.12.5/umd/popper.min.js"></script>
  <script src="https://cdn.bootcss.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>
<head>
<title>WebSocket的会话实现</title>
</head>


<body> <h2 style="text-align: center;">Welcome</h2>
<div style="margin-left: 7%;width: 50%;float: left;">
	<br />	<br />

    <input type="text" id="text" class="form-control" id="name" placeholder="发送消息内容">
	<button type="button" class="btn btn-info" onclick="send()" style="float: right;;">发送消息</button>

	<br /><hr>
	<!--userno:发送消息人的编号-->
	发送人:<div id="userno">${account}</div><br />
	接收人: <input type="text" id="usernoto"  
	class="form-control" id="name" placeholder="接受者">
	<br><br><br>
	<button onclick="closeWebSocket()">关闭WebSocket连接</button>
	<hr />
	</div>
	<div style="width: 40%;float: right;margin-top: 0%" id="message"></div>
	
</body>
 

<script type="text/javascript">
    var websocket = null;
    var userno=document.getElementById('userno').innerHTML;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("http://localhost:8080/sock/websocket/"+userno);
    }
    else {
        alert('当前浏览器 Not support websocket')
    }
 
    //连接发生错误的回调方法
    websocket.onerror = function () {
        setMessageInnerHTML("WebSocket连接发生错误");
    };


    //连接成功建立的回调方法
    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(sendMessage) {
        document.getElementById('message').innerHTML += sendMessage + '<br/>';
    }


    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }


    //发送消息
    function send() {
        var message = document.getElementById('text').value;//要发送的消息内容
        var now=getNowFormatDate();//获取当前时间
        document.getElementById('message').innerHTML += (now+"发送人:"+userno+'<br/>'+"---"+message) + '<br/>';
        document.getElementById('message').style.color="red";
        var ToSendUserno=document.getElementById('usernoto').value; //接收人编号:4567
        message=message+"|"+ToSendUserno//将要发送的信息和内容拼起来,以便于服务端知道消息要发给谁
        websocket.send(message);
    }
    //获取当前时间
    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                + " " + date.getHours() + seperator2 + date.getMinutes()
                + seperator2 + date.getSeconds();
        return currentdate;
} 
</script>
</html>

3702638926的会话页面,其中的发送人账号是登录时产生session的值,



熊大的登录和会话页面





后台数据接收




连接成功以后,就可以输入消息和对方的账号,既可以进行相互间的消息传递



以上就是websocket的简单功能实现!

第一次写不够标准,有部分也是参照网上学习的,所以部分会有重复的地方,谅解吧!

SSM框架,使用接口进行通信的我下一篇博客再写吧!

猜你喜欢

转载自blog.csdn.net/qq_38047600/article/details/80024696