websocket怎么说呢,就是服务器可以主动向客户端发起对话!
最新更新2021年8月20日15:48:05 内容:实现私信 这样就很好理解了吧! 咱们先上效果图: 相对来说更好看那么一点但是,实现代码都是一样的。我们先来准备工作导入依赖
<!--websocket依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
其实springboot已经内置了,直接在主函数启动就行。但我们这次就讲这个。导入依赖后 扫描启用
package com.nx.study.springstudy.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WS {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
**@ServerEndpoint("/websocket/{username}")**接收前端传回数据 @Component启用
package com.nx.study.springstudy.bean;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
@ServerEndpoint("/websocket/{username}")
@Component
public class Myws {
private static Map<String, Myws> webSocketSet = new ConcurrentHashMap<String, Myws>();
private static Map<String, Session> map = new HashMap<String, Session>();
private static List<String> namelist = new ArrayList<String>();
private static JSONObject jsonObject = new JSONObject();
private static JSONObject jsonObject2 = new JSONObject();
private static List<String> nm_msg = new ArrayList<String>();
private SocketMsg socketMsg;
private Session session;
private String name;
@OnOpen
public void onpen(Session session, @PathParam(value = "username") String username){
if(username == null){
username = "游客";
}
this.session = session;
// this.name = "南" + getname();
this.name = username;
webSocketSet.put(name, this);
map.put(username, session);
namelist.clear(); // 清空原来的信息
setonlion();
jsonObject.put("onlinepp", namelist);
String message = jsonObject.toString();
broadcast2(message);
}
@OnClose
public void onclose(){
webSocketSet.remove(this.name); // 移除对象
namelist.clear();
setonlion();
jsonObject.clear();
jsonObject.put("onlinepp", namelist);
String message = jsonObject.toString();
broadcast3(message);
}
@OnMessage
public void onmessage(String message){
nm_msg.clear();
jsonObject2.clear();
nm_msg.add(name);
nm_msg.add(message);
jsonObject2.put("chat", nm_msg);
String message2 = jsonObject2.toString();
broadcast(message2);
}
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
public void broadcast(String message){
for (Map.Entry<String, Myws> item : webSocketSet.entrySet()){
item.getValue().session.getAsyncRemote().sendText(message);
}
}
public void broadcast2(String message){
for (Map.Entry<String, Myws> item : webSocketSet.entrySet()){
item.getValue().session.getAsyncRemote().sendText(message);
}
}
public void broadcast3(String message){
for (Map.Entry<String, Myws> item : webSocketSet.entrySet()){
if (!item.getKey().equals(name)){
item.getValue().session.getAsyncRemote().sendText(message);
}
}
}
public void setonlion(){
for (Map.Entry<String, Myws> item : webSocketSet.entrySet()){
namelist.add(item.getKey());
}
}
public String getname() {
String linkNo = "";
// 用字符数组的方式随机
String model = "小大天明画美丽豪子余多少浩然兄弟朋友美韵紫萱好人坏蛋误解不要停栖栖遑遑可";
char[] m = model.toCharArray();
for (int j = 0; j < 2; j++) {
char c = m[(int) (Math.random() * 36)];
// 保证六位随机数之间没有重复的
if (linkNo.contains(String.valueOf(c))) {
j--;
continue;
}
linkNo = linkNo + c;
}
return linkNo;
}
}
其中重点就是4个注解**@OnOpen,@OnClose,@OnMessage,@OnError** @OnOpen–>客户端打开链接时候触发执行 @OnClose–>客户端关闭链接触发执行 @OnMessage–>客户端发送信息触发执行 @OnError–>发送错误时候触发执行
对象信息都储存在Session,可以仔细看看上面代码很好理解。我们只需要理解这4个注解的作用就可以! 我们的前端页面来了代码如下
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<link rel="icon" type="image/x-icon" th:href="@{/img/user/head/favicon.ico}" />
<script th:src="@{webjars/jquery/3.1.1/jquery.min.js}"></script>
<script th:src="@{webjars/bootstrap/3.3.7/js/bootstrap.min.js}"></script>
<link rel="stylesheet" th:href="@{webjars/bootstrap/3.3.7/css/bootstrap.min.css}" />
<link th:href="@{/css/home.css}" rel="stylesheet" type="text/css" />
<meta charset="UTF-8">
<title>在线聊天室</title>
</head>
<body>
<div class="container-fluid">
<div style="width: 100%;height: 100px;text-align: center;margin-bottom: 30px;color: #495e6a;box-shadow: 0px 0px 10px #000000">
<br>
<h1>文明用语,快乐你我他</h1>
</div>
<div style="width: 800px;height: 600px;margin: auto;background-color: #dce9f6;box-shadow: 0px 0px 10px #707074;display: flex">
<div style="width: 200px;height: 600px;background-color: #d4d1d1">
<div style="width: 160px;height: 40px;margin: auto;margin-top: 10px;background-color: #fdffff;text-align: center;box-shadow: 0px 0px 10px #474749;border-radius: 4px">
<span class="glyphicon glyphicon-globe" style="font-size: 30px;padding-top: 2px;padding-bottom: 2px"></span>
<span style="font-size: 30px">群聊</span>
</div>
<div style="width: 160px;height: 40px;margin: auto;margin-top: 10px;background-color: #fdffff;text-align: center;box-shadow: 0px 0px 10px #474749;border-radius: 4px">
<span class="glyphicon glyphicon-star" style="font-size: 30px;padding-top: 2px;padding-bottom: 2px"></span>
<span style="font-size: 30px" th:text="${Springuser.username}">游客</span>
</div>
<hr>
<div id="online" style="width: 200px;height: 500px;word-break: break-word;overflow: auto">
</div>
</div>
<div style="width: 600px;height: 600px">
<div style="width: 600px;height: 500px;padding: 20px 20px 20px 20px;word-break: break-word;overflow: auto" id="message">
</div>
<div style="width: 600px;height: 100px;background-color: #ddf1d7;display: flex">
<div style="width: 100px;height: 100px;text-align: center;background-color: #f5d2d2">
<button id="btn1" class="btn btn-success" style="margin-top: 5px">连接上线</button><br>
<br>
<button id="btn2" class="btn btn-danger">下线</button>
</div>
<div style="width: 500px;height: 100px;padding: 10px 10px 10px 10px" class="input-group">
<input id="msg" type="text" class="form-control" placeholder="在这里输入想说的话吧!" /><br>
<button id="btn3" class="btn btn-info" style="margin-top: 10px;float: right">发送消息</button>
</div>
</div>
</div>
</div>
<div class="div2" style="margin-top: 30px;background-color: #ffffff">
<br><br>
<a href="#"><span style="color: #000000;">关于我们</span></a> |
<a href="mailto: 2251798294@qq.com" style="color: #000000;">找我合作</a><br>
<a href="http://beian.miit.gov.cn" style="color: #202223;">赣ICP备2021004042号</a>
</div>
</div>
</body>
<script th:inline="javascript" language='javascript'>
$(document).ready(function(){
var select;
var message = "";
var fromuser = "";
var touser = "";
var type = 0;
var username = [[${Springuser.username}]];
var websocket = null;
$("#btn1").click(function(){
//判断当前浏览器是否支持WebSocket
if(select === 1){
alert("你已连接上线路,无需重复连接!")
}else {
if ('WebSocket'in window) {
websocket = new WebSocket("ws://wenhaosuper.top:8000/websocket/" + username);
alert("欢迎-->" + username + "<--成功上线!");
select = 1;
} else {
alert('Not support websocket')
}
}
//连接发生错误的回调方法
websocket.onerror = function() {
alert("错误");
};
//连接成功建立的回调方法
websocket.onopen = function() {
}
//接收到消息的回调方法
websocket.onmessage = function(event) {
var msg = event.data
var obj = JSON.parse(msg);
var zxname = obj.onlinepp;
var chat = obj.chat;
if (zxname != null){
onlinename(zxname);
}
if (chat != null){
setchat(chat);
}
}
//连接关闭的回调方法
websocket.onclose = function() {
alert("离开");
select = 2;
$("#online").empty();
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
websocket.onclose;
websocket.close();
}
});
//将消息显示在网页上
function setchat(message) {
$("<div style=\"width: 560px;min-height: 40px;display: flex;margin-bottom: 20px\">\n" +
" <div style=\"width: 40px;height: 40px;background-color: #ffffff;text-align: center;border-radius: 20px\">\n" +
" <span style=\"font-size: 28px;margin-top: 9px\"><strong>N</strong></span>\n" +
" </div>\n" +
" <div style=\"min-height: 40px;margin-left: 10px\">\n" +
" <div style=\"height: 18px\">\n" +
" <span style=\"color: #7f7777;font-size: 14px\">"+message[0]+"</span>\n" +
" </div>\n" +
" <div style=\"min-height: 20px;word-break: break-word;background-color: #ffffff;padding: 10px 10px 10px 10px;border-radius: 6px\">\n" +
" <span>"+message[1]+"</span>\n" +
" </div>\n" +
" </div>\n" +
" </div>").appendTo("#message");
}
function onlinename(obj){
$("#online").empty();
obj.forEach(function (e){
$("<div style=\"width: 160px;height: 40px;margin: auto;margin-top: 10px;background-color: #fdffff;text-align: center;box-shadow: 0px 0px 10px #474749;border-radius: 4px;overflow: hidden\">\n" +
" <span class=\"glyphicon glyphicon-user\" style=\"font-size: 30px;padding-top: 2px;padding-bottom: 2px\"></span>\n" +
" <span style=\"font-size: 26px\">"+e+"</span>\n" +
" </div>").appendTo("#online");
});
}
$("#btn2").click(function(){
websocket.close();
});
//发送消息
$("#btn3").click(function(){
var message = $("#msg").val();
websocket.send(message);
$("#msg").val("");
});
});
</script>
</html>
前端基础着实差了一点!哈哈哈 当然因为我这个是springboot项目,我用了模板引擎 代码如下
package com.nx.study.springstudy.controller;
import com.nx.study.springstudy.bean.UserPostForm;
import com.nx.study.springstudy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Controller
public class WebSocketController {
@Autowired
private UserService userService;
@RequestMapping("/websocket")
public String webSocket(Model model, HttpServletRequest request){
HttpSession httpSession = request.getSession();
String username = (String) request.getSession().getAttribute("username");
String userpassword = (String) request.getSession().getAttribute("userpassword");
if (username != null){
UserPostForm Springuser = userService.query(username,userpassword);
model.addAttribute("Springuser", Springuser);
return "index/webSocket";
}else {
return "index/ZGZG";
}
}
}
最后就放几张效果图吧 后续问题解答—> 就是在项目打包的时候,会出现打包失败抛出一个错误。对于这个问题我也是在网上查找了一番。最终锁定问题!
就是springboot里面已经内置了websocket相关服务,我们重新导入的依赖会冲突。
解决办法我们在pom.xml文件里面添加一串代码
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
位置》
最新最全教程来了
更新时间2021年8月20日15:49:48 最新更新了私信功能!实现私信功能!实现私信功能!
- 首先我们来看看效果图
我重新添加了两个按钮,一个是群聊,一个是私聊,我们进入页面初始化的页面就是群聊,我们点击私聊进入后可以看见如图·: 选择你想要私聊的对象就可以与他私聊!想要回到群聊,我们就点击群聊按钮就可以了。
- 代码分析
这个地方我加了一个类型判断,判断是群聊,还是私聊
这两个按钮就是来控制页面是群聊还是私聊的还进行了变量的控制 然后就是发送消息的按钮进行修改 我们现在去后端看看代码 后端代码更改地方就这些。现在我们来看看全部代码
后端
package com.nx.study.springstudy.bean;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
@ServerEndpoint("/websocket/{username}")
@Component
public class Myws {
private static Map<String, Myws> webSocketSet = new ConcurrentHashMap<String, Myws>();
private static Map<String, Session> map = new HashMap<String, Session>();
private static List<String> namelist = new ArrayList<String>();
private static JSONObject jsonObject = new JSONObject();
private static JSONObject jsonObject2 = new JSONObject();
private static List<String> nm_msg = new ArrayList<String>();
private SocketMsg socketMsg;
private Session session;
private String name;
@OnOpen
public void onpen(Session session, @PathParam(value = "username") String username){
if(username == null){
username = "游客";
}
this.session = session;
// this.name = "南" + getname();
this.name = username;
webSocketSet.put(name, this);
map.put(username, session);
namelist.clear(); // 清空原来的信息
setonlion();
jsonObject.put("onlinepp", namelist);
String message = jsonObject.toString();
broadcast2(message);
}
@OnClose
public void onclose(){
webSocketSet.remove(this.name); // 移除对象
namelist.clear();
setonlion();
jsonObject.clear();
jsonObject.put("onlinepp", namelist);
String message = jsonObject.toString();
broadcast3(message);
}
@OnMessage
public void onmessage(String message){
String[] message2 = message.split("-");
String type = message2[0];
String newmessage = message2[1];
String tousername = message2[2];
if(type.equals("q")){
nm_msg.clear();
jsonObject2.clear();
nm_msg.add(name);
nm_msg.add(newmessage);
nm_msg.add("q"); // 判断
nm_msg.add(tousername); // 占位置防止报错
jsonObject2.put("chat", nm_msg);
String message3 = jsonObject2.toString();
broadcast(message3);
}else if(type.equals("s")){
nm_msg.clear();
jsonObject2.clear();
nm_msg.add(name);
nm_msg.add(newmessage);
nm_msg.add("s");
nm_msg.add(tousername);
jsonObject2.put("chat", nm_msg);
String message3 = jsonObject2.toString();
broadcast4(message3, tousername);
}
}
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
public void broadcast(String message){
for (Map.Entry<String, Myws> item : webSocketSet.entrySet()){
item.getValue().session.getAsyncRemote().sendText(message);
}
}
public void broadcast2(String message){
for (Map.Entry<String, Myws> item : webSocketSet.entrySet()){
item.getValue().session.getAsyncRemote().sendText(message);
}
}
public void broadcast3(String message){
for (Map.Entry<String, Myws> item : webSocketSet.entrySet()){
if (!item.getKey().equals(name)){
item.getValue().session.getAsyncRemote().sendText(message);
}
}
}
public void broadcast4(String message, String tousername){ // 私聊
webSocketSet.get(tousername).session.getAsyncRemote().sendText(message); // 接收者
webSocketSet.get(name).session.getAsyncRemote().sendText(message); // 发送者
}
public void setonlion(){
for (Map.Entry<String, Myws> item : webSocketSet.entrySet()){
namelist.add(item.getKey());
}
}
public String getname() {
String linkNo = "";
// 用字符数组的方式随机
String model = "小大天明画美丽豪子余多少浩然兄弟朋友美韵紫萱好人坏蛋误解不要停栖栖遑遑可";
char[] m = model.toCharArray();
for (int j = 0; j < 2; j++) {
char c = m[(int) (Math.random() * 36)];
// 保证六位随机数之间没有重复的
if (linkNo.contains(String.valueOf(c))) {
j--;
continue;
}
linkNo = linkNo + c;
}
return linkNo;
}
}
前端
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<link rel="icon" type="image/x-icon" th:href="@{/img/user/head/favicon.ico}" />
<script th:src="@{webjars/jquery/3.1.1/jquery.min.js}"></script>
<script th:src="@{webjars/bootstrap/3.3.7/js/bootstrap.min.js}"></script>
<link rel="stylesheet" th:href="@{webjars/bootstrap/3.3.7/css/bootstrap.min.css}" />
<link th:href="@{/css/home.css}" rel="stylesheet" type="text/css" />
<meta charset="UTF-8">
<title>在线聊天室</title>
</head>
<body>
<div class="container-fluid">
<div style="width: 100%;height: 100px;text-align: center;margin-bottom: 30px;color: #495e6a;box-shadow: 0px 0px 10px #000000">
<br>
<h1>文明用语,快乐你我他</h1>
</div>
<div style="width: 800px;height: 600px;margin: auto;background-color: #dce9f6;box-shadow: 0px 0px 10px #707074;display: flex">
<div style="width: 200px;height: 600px;background-color: #d4d1d1">
<div style="width: 160px;height: 40px;margin: auto;margin-top: 10px;text-align: center">
<!-- <span class="glyphicon glyphicon-globe" style="font-size: 30px;padding-top: 2px;padding-bottom: 2px"></span>-->
<!-- <span style="font-size: 30px">群聊</span>-->
<button id="btn4" class="btn btn-danger" style="margin-top: 10px;float: left">私信</button>
<button id="btn5" class="btn btn-success" style="margin-top: 10px;float: right">群聊</button>
</div>
<div style="width: 160px;height: 40px;margin: auto;margin-top: 10px;background-color: #fdffff;text-align: center;box-shadow: 0px 0px 10px #474749;border-radius: 4px">
<span class="glyphicon glyphicon-star" style="font-size: 30px;padding-top: 2px;padding-bottom: 2px"></span>
<span style="font-size: 30px" th:text="${Springuser.username}">游客</span>
</div>
<hr>
<div id="online" style="width: 200px;height: 500px;word-break: break-word;overflow: auto">
</div>
</div>
<div style="width: 600px;height: 600px">
<div style="width: 600px;height: 500px;padding: 20px 20px 20px 20px;word-break: break-word;overflow: auto" id="message">
</div>
<div style="width: 600px;height: 500px;padding: 20px 20px 20px 20px;word-break: break-word;overflow: auto;display: none;background-color: #efcbc0" id="message2">
<div style="width: 560px;height: 40px;text-align: center">
<select class="btn btn-default dropdown-toggle" id="selectname">
</select>
</div>
<hr>
</div>
<div style="width: 600px;height: 100px;background-color: #ddf1d7;display: flex">
<div style="width: 100px;height: 100px;text-align: center;background-color: #f5d2d2">
<button id="btn1" class="btn btn-success" style="margin-top: 5px">连接上线</button><br>
<br>
<button id="btn2" class="btn btn-danger">下线</button>
</div>
<div style="width: 500px;height: 100px;padding: 10px 10px 10px 10px" class="input-group">
<input id="msg" type="text" class="form-control" placeholder="在这里输入想说的话吧!" /><br>
<button id="btn3" class="btn btn-info" style="margin-top: 10px;float: right">发送消息</button>
</div>
</div>
</div>
</div>
<div class="div2" style="margin-top: 30px;background-color: #ffffff">
<br><br>
<a href="#"><span style="color: #000000;">关于我们</span></a> |
<a href="mailto: 2251798294@qq.com" style="color: #000000;">找我合作</a><br>
<a href="http://beian.miit.gov.cn" style="color: #202223;">赣ICP备2021004042号</a>
</div>
</div>
</body>
<script th:inline="javascript" language='javascript'>
$(document).ready(function(){
var select;
var fromuser = "";
var type = "q";
var username = [[${Springuser.username}]];
var websocket = null;
$("#btn1").click(function(){
//判断当前浏览器是否支持WebSocket
if(select === 1){
alert("你已连接上线路,无需重复连接!")
}else {
if ('WebSocket'in window) {
// wenhaosuper.top:8000
websocket = new WebSocket("ws://wenhaosuper.top:8000/websocket/" + username);
alert("欢迎-->" + username + "<--成功上线!");
select = 1;
} else {
alert('Not support websocket')
}
}
//连接发生错误的回调方法
websocket.onerror = function() {
alert("错误");
};
//连接成功建立的回调方法
websocket.onopen = function() {
}
//接收到消息的回调方法
websocket.onmessage = function(event) {
var touser = $("#selectname").val();
var msg = event.data
var obj = JSON.parse(msg);
var zxname = obj.onlinepp;
var chat = obj.chat;
if (zxname != null){
onlinename(zxname);
}
if (chat != null){
if (chat[2] === "q"){
setchat(chat);
}else if (chat[2] === "s" && chat[3] === username){
setchat2(chat);
}else if(chat[2] === "s" && chat[3] === touser){
setchat2(chat);
}
}
}
//连接关闭的回调方法
websocket.onclose = function() {
alert("离开");
select = 2;
$("#online").empty();
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
websocket.onclose;
websocket.close();
}
});
//将消息显示在网页上 // 群聊
function setchat(message) {
$("<div style=\"width: 560px;min-height: 40px;display: flex;margin-bottom: 20px\">\n" +
" <div style=\"width: 40px;height: 40px;background-color: #ffffff;text-align: center;border-radius: 20px\">\n" +
" <span style=\"font-size: 28px;margin-top: 9px\"><strong>N</strong></span>\n" +
" </div>\n" +
" <div style=\"min-height: 40px;margin-left: 10px\">\n" +
" <div style=\"height: 18px\">\n" +
" <span style=\"color: #7f7777;font-size: 14px\">"+message[0]+"</span>\n" +
" </div>\n" +
" <div style=\"min-height: 20px;word-break: break-word;background-color: #ffffff;padding: 10px 10px 10px 10px;border-radius: 6px\">\n" +
" <span>"+message[1]+"</span>\n" +
" </div>\n" +
" </div>\n" +
" </div>").appendTo("#message");
}
//将消息显示在网页上 // 私聊
function setchat2(message) {
$("<div style=\"width: 560px;min-height: 40px;display: flex;margin-bottom: 20px\">\n" +
" <div style=\"width: 40px;height: 40px;background-color: #ffffff;text-align: center;border-radius: 20px\">\n" +
" <span style=\"font-size: 28px;margin-top: 9px\"><strong>N</strong></span>\n" +
" </div>\n" +
" <div style=\"min-height: 40px;margin-left: 10px\">\n" +
" <div style=\"height: 18px\">\n" +
" <span style=\"color: #7f7777;font-size: 14px\">"+message[0]+"</span>\n" +
" </div>\n" +
" <div style=\"min-height: 20px;word-break: break-word;background-color: #ffffff;padding: 10px 10px 10px 10px;border-radius: 6px\">\n" +
" <span>"+message[1]+"</span>\n" +
" </div>\n" +
" </div>\n" +
" </div>").appendTo("#message2");
}
function onlinename(obj){
$("#online").empty();
$("#selectname").empty();
obj.forEach(function (e){
$("<div style=\"width: 160px;height: 40px;margin: auto;margin-top: 10px;background-color: #fdffff;text-align: center;box-shadow: 0px 0px 10px #474749;border-radius: 4px;overflow: hidden\">\n" +
" <span class=\"glyphicon glyphicon-user\" style=\"font-size: 30px;padding-top: 2px;padding-bottom: 2px\"></span>\n" +
" <span style=\"font-size: 26px\">"+e+"</span>\n" +
" </div>").appendTo("#online");
$("<option value="+e+">"+e+"</option>").appendTo("#selectname");
});
}
$("#btn2").click(function(){
websocket.close();
});
//发送消息
$("#btn3").click(function(){
var touser = $("#selectname").val();
if (touser == null){
alert("你必须选择一位好友,或者自己和自己聊聊天?");
}else {
var message = type + "-" + $("#msg").val() + "-" + touser;
websocket.send(message);
$("#msg").val("");
}
});
$("#btn4").click(function (){ // 私聊
type = "s";
$("#message").hide();
$("#message2").show();
});
$("#btn5").click(function (){ // 群聊
type = "q";
$("#message").show();
$("#message2").hide();
});
});
</script>
</html>
嗯嗯就大概上面这么多了前端要注意几个我更改的地方
- 最后大家欣赏一下效果图吧
**
最新更新
时间2021年8月20日23:10:51 因为收到很多小伙伴是私信,要求给githup链接,好的今天它来了,我重新新建了一个项目单独把这个功能拉出来了,大家自行下载!下载后用idea打开就可以。然后浏览器打开页面就可以了
githup链接献上:https://github.com/nanxiang11/WebSocket_Test
如果大家有不懂的地方可以随时了私信我哦!感谢
|