个人博客

2021年5月3日:

今天学习了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>
<head>
<title>Java后端WebSocket的Tomcat实现</title>
</head>
<body>
    Welcome
<br />
<input id="text" type="text" />    
<button οnclick="send()">发送消息</button>
<hr />
   
<!--userno:发送消息人的编号-->
    发送人:
<div id="userno">1234</div>
    接收人:
<input type="text" id="usernoto">
<br>    
<button οnclick="closeWebSocket()">关闭WebSocket连接</button>
   
<hr />
   
<div id="message"></div>
</body>


<script type="text/javascript">
    var websocket = null;
    var userno=document.getElementById('userno').innerHTML;

   websocket = new WebSocket("ws://localhost:8080/ssm-crud/websocket/"+userno);
    //连接发生错误的回调方法
    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>

 

后端服务器代码:

 

package com.atguigu.crud.utils;

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

@ServerEndpoint("/websocket/{userno}")
@Component
public class websocket {
private static int onlineCount = 0;

private static ConcurrentHashMap<String, websocket> webSocketSet = new ConcurrentHashMap<String, websocket>();

private Session WebSocketsession;

private String userno = "";

private static int i;

@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();
System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
}

@OnClose
public void onClose() {
if (!userno.equals("")) {
webSocketSet.remove(userno);
subOnlineCount();
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
}

@SuppressWarnings("unused")
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
if (1 < 2) {
sendAll(message);
} else {
sendToUser(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();
}
}

private void sendAll(String message) {
String now = getNowTime();
String sendMessage = message.split("[|]")[0];

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();
}
}
}

private String getNowTime() {
Date date = new Date();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = format.format(date);
return time;
}

@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}

public void sendMessage(String message) throws IOException {
this.WebSocketsession.getBasicRemote().sendText(message);
}

public static synchronized int getOnlineCount() {
return onlineCount;
}

public static synchronized void addOnlineCount() {
websocket.onlineCount++;
}

public static synchronized void subOnlineCount() {
websocket.onlineCount--;
}
}

今天找了很久的样例才找到了这个代码,至于怎么运行的现在还不知道,这几天打算先把websocket搞懂在来搞系统通信。

posted @ 2021-05-03 19:46  一条快乐的小鲸鱼  阅读(76)  评论(0编辑  收藏  举报