1、简单说明

在网上看到一份比较nice的基于webSocket网页聊天项目,准备看看学习学习,如是有了这篇文章!原博主博客:http://blog.csdn.net/Amayadream/article/details/50551617

谢谢博主的文章和项目,我是抱着学习的态度,若有理解错的地方,请指正。

2、项目内容

项目的功能说明去原博主博客看吧,项目上改进的地方,我具体做以下说明。

(1)webSocket服务

对于webSocket服务代码,我进行一部分的封装和优化,主要是消息内容的封装、用户信息封装。

页面显示用户的昵称,指定用户昵称进行消息发送。

ChatServer.java

package com.ccq.webSocket;

import com.ccq.pojo.User;
import com.ccq.utils.CommonDate;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger; import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; /**
* @author ccq
* @Description webSocket服务
* @date 2017/12/16 17:31
*/
@ServerEndpoint(value="/chatServer/{userid}", configurator = HttpSessionConfigurator.class)
public class ChatServer { private static Logger logger = Logger.getLogger(ChatServer.class);
private static int onlineCount = ; // 记录连接数目
// Map<用户id,用户信息>
private static Map<String, OnlineUser> onlineUserMap = new ConcurrentHashMap<String, OnlineUser>(); //在线用户 /**
* 连接成功调用的方法
*/
@OnOpen
public void onOpen(@PathParam("userid") String userid , Session session, EndpointConfig config){ logger.info("[ChatServer] connection : userid = " + userid + " , sessionId = " + session.getId()); // 增加用户数量
addOnlineCount(); // 获取当前用户的session
HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
User user = (User) httpSession.getAttribute("user"); // 获得当前用户信息 // 将当前用户存到在线用户列表中
OnlineUser onlineUser = new OnlineUser(user.getUserid(),user.getNickname(),session);
onlineUserMap.put(user.getUserid(),onlineUser); // 通知所有在线用户,当前用户上线
String content = "[" + CommonDate.getTime24() + " : " + user.getNickname() + "加入聊天室,当前在线人数为 " + getOnlineCount() + "位" + "]";
JSONObject msg = new JSONObject();
msg.put("content",content);
String message = Message.getMessage(msg.toString(),Message.NOTICE,onlineUserMap.values());
Message.broadcast(message,onlineUserMap.values()); } /**
* 连接关闭方法
*/
@OnClose
public void onClose(@PathParam("userid") String userid,Session session,CloseReason closeReason){ logger.info("[ChatServer] close : userid = " + userid + " , sessionId = " + session.getId() +
" , closeCode = " + closeReason.getCloseCode().getCode() + " , closeReason = " +closeReason.getReasonPhrase()); // 减少当前用户
subOnlienCount(); // 移除的用户信息
OnlineUser removeUser = onlineUserMap.remove(userid);
onlineUserMap.remove(userid); // 通知所有在线用户,当前用户下线
String content = "["+ CommonDate.getTime24() + " : " + removeUser.getNickname() + " 离开聊天室,当前在线人数为 " + getOnlineCount() + "位" + "]";
JSONObject msg = new JSONObject();
msg.put("content",content);
if(onlineUserMap.size() > ){
String message = Message.getMessage(msg.toString(), Message.NOTICE, onlineUserMap.values());
Message.broadcast(message,onlineUserMap.values());
}else{
logger.info("content : ["+ CommonDate.getTime24() + " : " + removeUser.getNickname() + " 离开聊天室,当前在线人数为 " + getOnlineCount() + "位" + "]");
} } /**
* 接收客户端的message,判断是否有接收人而选择进行广播还是指定发送
* @param data 客户端发来的消息
*/
@OnMessage
public void onMessage(@PathParam("userid") String userid,String data){
logger.info("[ChatServer] onMessage : userid = " + userid + " , data = " + data); JSONObject messageJson = JSONObject.fromObject(data);
JSONObject message = messageJson.optJSONObject("message");
String to = message.optString("to");
String from = message.optString("from");
// 将用户id转换为名称
to = this.userIdCastNickName(to); OnlineUser fromUser = onlineUserMap.get(from);
String sendMessage = Message.getContent(fromUser,to,message.optString("content"),message.optString("time"));
String returnData = Message.getMessage(sendMessage, messageJson.optString("type"),null); if(to == null || to.equals("")){ // 进行广播
Message.broadcast(returnData.toString(),onlineUserMap.values());
}else{
Message.singleSend(returnData.toString(), onlineUserMap.get(from)); // 发送给自己
String[] useridList = message.optString("to").split(",");
for(String id : useridList){
if(!id.equals(from)){
Message.singleSend(returnData.toString(), onlineUserMap.get(id)); // 分别发送给指定的用户
}
}
}
} /**
* 发生错误
* @param throwable
*/
@OnError
public void onError(@PathParam("userid") String userid,Session session,Throwable throwable){
logger.info("[ChatServer] close : userid = " + userid + " , sessionId = " + session.getId() +" , throwable = " + throwable.getMessage() );
} public static int getOnlineCount() {
return onlineCount;
} public synchronized void addOnlineCount(){
onlineCount++;
} public synchronized void subOnlienCount(){
onlineCount--;
} /**
* 将用户id转换为名称
* @param userIds
* @return
*/
private String userIdCastNickName(String userIds){
String niceNames = "";
if(userIds != null && !userIds.equals("")){
String[] useridList = userIds.split(",");
String toName = "";
for (String id : useridList){
toName = toName + onlineUserMap.get(id).getNickname() + ",";
}
niceNames = toName.substring(,toName.length() - );
}
return niceNames;
}
}

OnlineUser.java

public class OnlineUser {
private String userid;
private String nickname;
private Session session;
}

  Message.java

package com.ccq.webSocket;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger; import javax.websocket.Session;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List; /**
* @author ccq
* @Description 消息类
* @date 2017/12/16 19:08
*/
public class Message { private static Logger logger = Logger.getLogger(Message.class); /**
* 消息类型
*/
public static String NOTICE = "notice"; //通知
public static String MESSAGE = "message"; //消息 /**
* 组装信息返回给前台
* @param message 交互信息
* @param type 信息类型
* @param userList 在线列表
* @return
*
* "massage" : {
* "from" : "xxx",
* "to" : "xxx",
* "content" : "xxx",
* "time" : "xxxx.xx.xx"
* },
* "type" : {notice|message},
* "list" : {[xx],[xx],[xx]}
*/
public static String getMessage(String message,String type,Collection<OnlineUser> userList){
JSONObject msg = new JSONObject();
msg.put("message",message);
msg.put("type", type); if(CollectionUtils.isNotEmpty(userList)){
List<String> propertys = new ArrayList<String>();
propertys.add("session");
JSONArray userListArray = JSONArray.fromObject(userList,JsonConfigUtils.getJsonConfig(propertys));
msg.put("list", userListArray);
}
return msg.toString();
} /**
* 消息内容
* @param fromUser
* @param to
* @param content
* @param time
* @return
* {
* "from" : "xxx",
* "to" : "xxx",
* "content" : "xxx",
* "time" : "xxxx.xx.xx"
* }
*/
public static String getContent(OnlineUser fromUser,String to,String content,String time){
JSONObject contentJson = new JSONObject(); // 转化为json串时去掉session,用户session不能被序列化
List<String> propertys = new ArrayList<String>();
propertys.add("session");
contentJson.put("from",JSONObject.fromObject(fromUser,JsonConfigUtils.getJsonConfig(propertys))); contentJson.put("to",to);
contentJson.put("content",content);
contentJson.put("time",time);
return contentJson.toString();
} /**
* 广播消息
* @param message 消息
* @param onlineUsers 在线用户
*/
public static void broadcast(String message,Collection<OnlineUser> onlineUsers){
/***************************在线用户***************************/
StringBuffer userStr = new StringBuffer();
for(OnlineUser user : onlineUsers){
userStr.append(user.getNickname() + ",");
}
userStr.deleteCharAt(userStr.length()-);
logger.info("[broadcast] message = " + message + ", onlineUsers = " + userStr.toString());
/***************************在线用户***************************/
for(OnlineUser user : onlineUsers){
try {
user.getSession().getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
logger.info("消息发送失败!" + e.getMessage());
continue;
}
}
} /**
* 对特定用户发送消息
* @param message
* @param onlineUser
*/
public static void singleSend(String message, OnlineUser onlineUser){
logger.info("[singleSend] message = " + message + ", toUser = " + onlineUser.getNickname());
try {
onlineUser.getSession().getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
logger.info("消息发送失败!" + e.getMessage());
}
}
}

(2)用户头像上传

在网上找了一个amazeui的图片上传,可以对图片进行裁剪,地址:http://www.jq22.com/jquery-info13022

确实比较好用,贴一下主要代码

@RequestMapping(value = "{userid}/upload", method = RequestMethod.POST,produces = "application/json; charset=utf-8")
@ResponseBody
public String updateUserPassword(@PathVariable("userid") String userid,String image,HttpServletRequest request){ JSONObject responseJson = new JSONObject();
String filePath = "I:\\IDEA2017-02\\img\\";
String PicName= UUID.randomUUID().toString()+".png"; String header ="data:image";
String[] imageArr=image.split(",");
if(imageArr[].contains(header)) {//是img的 // 去掉头部
image=imageArr[];
// 修改图片
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] decodedBytes = decoder.decodeBuffer(image); // 将字符串格式的image转为二进制流(biye[])的decodedBytes
String imgFilePath = filePath + PicName; //指定图片要存放的位
File targetFile = new File(filePath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(imgFilePath);//新建一个文件输出器,并为它指定输出位置imgFilePath
out.write(decodedBytes); //利用文件输出器将二进制格式decodedBytes输出
out.close();
// 修改图片
User user = userService.getUserById(userid);
user.setProfilehead(PicName);
int flag = userService.updateUser(user);
if(flag > ){
Log log = LogUtil.setLog(userid, CommonDate.getTime24(), WordDefined.LOG_TYPE_UPDATE,WordDefined.LOG_DETAIL_UPDATE_PROFILEHEAD, NetUtil.getIpAddress(request));
logService.insertLog(log);
}else{
responseJson.put("result","error");
responseJson.put("msg","上传失败!");
}
} catch (IOException e) {
e.printStackTrace();
}
} responseJson.put("result","ok");
responseJson.put("msg","上传成功!");
responseJson.put("fileUrl","/pic/" + PicName);
return responseJson.toString();
}

3、改进的图片

4、源码地址(2017-12-17晚更新)

由于小弟刚学会使用github,所以现在才把修改的代码地址放出来。

源码github地址:https://github.com/chengchuanqiang/WebChat

说明一下:

1、github是一个好东西,有时间学习一下如何使用git版本管理工具还是蛮有用的,有需要的视频的我可以免费发给你;

2、使用maven+idea开发项目确实很带劲;

3、老老实实学习,快快乐乐进步。

Java WebSocket实现网络聊天室(群聊+私聊)的更多相关文章

  1. Java 网络编程 -- 基于TCP 实现聊天室 群聊 私聊

    分析: 聊天室需要多个客户端和一个服务端. 服务端负责转发消息. 客户端可以发送消息.接收消息. 消息分类: 群聊消息:发送除自己外所有人 私聊消息:只发送@的人 系统消息:根据情况分只发送个人和其他 ...

  2. JAVA WebSocKet ( 简单的聊天室 )

    1, 前端代码 登入页 -> login.html <!DOCTYPE html> <html> <head> <meta charset=" ...

  3. Java TCP案例网络聊天室

    收获:1,加深了对多线程的一边一边的理解,可以将行为写成不同的类然后多线程 2,IO流的复习! 3,多线程中一边读取一边操作时容器最好(CopyOnWriteArrayList); 4,Tcp流程的熟 ...

  4. Java WebSocket实现简易聊天室

    一.Socket简介 Socket又称"套接字",应用程序通常通过"套接字"向网络发出请求或者应答网络请求.Socket的英文原义是“孔”或“插座”,作为UNI ...

  5. swoole websocket_server 聊天室--群聊

    centos7  php7.2 swoole4.3 nginx1.8 websocket_server 代码 <?php $server = new Swoole\WebSocket\Serve ...

  6. 基于WebSocket的简易聊天室

    用的是Flash + WebSocket 哦~ Flask 之 WebSocket 一.项目结构: 二.导入模块 pip3 install gevent-websocket 三.先来看一个一对一聊天的 ...

  7. php websocket-网页实时聊天之PHP实现websocket(ajax长轮询和websocket都可以时间网络聊天室)

    php websocket-网页实时聊天之PHP实现websocket(ajax长轮询和websocket都可以时间网络聊天室) 一.总结 1.ajax长轮询和websocket都可以时间网络聊天室 ...

  8. Java和WebSocket开发网页聊天室

    小编心语:咳咳咳,今天又是聊天室,到现在为止小编已经分享了不下两个了,这一次跟之前的又不大相同,这一次是网页聊天室,具体怎么着,还请各位看官往下看~ Java和WebSocket开发网页聊天室 一.项 ...

  9. 分享基于 websocket 网页端聊天室

    博客地址:https://ainyi.com/67 有一个月没有写博客了,也是因为年前需求多.回家过春节的原因,现在返回北京的第二天,想想,应该也要分享技术专题的博客了!! 主题 基于 websock ...

随机推荐

  1. springmvc 无法访问静态资源

    没有配置<mvc:resources location="/" mapping="/**"/> <?xml version="1.0 ...

  2. P1101 单词方阵 简单dfs

    题目描述 给一n \times nn×n的字母方阵,内可能蕴含多个“yizhong”单词.单词在方阵中是沿着同一方向连续摆放的.摆放可沿着 88 个方向的任一方向,同一单词摆放时不再改变方向,单词与单 ...

  3. API接口设计,rest,soap

    REST之前的重要协议SOAP rest(简单理解风格.约束.设计理念) rest之前是SOAP:SOAP Web API采用RPC风格,它采用面向功能的架构,所以我们在设计SOAP Web API的 ...

  4. TF之NN:matplotlib动态演示深度学习之tensorflow将神经网络系统自动学习并优化修正并且将输出结果可视化—Jason niu

    import tensorflow as tf import numpy as np import matplotlib.pyplot as plt def add_layer(inputs, in_ ...

  5. Radar Installation POJ - 1328(贪心)

    Assume the coasting is an infinite straight line. Land is in one side of coasting, sea in the other. ...

  6. 002.Zabbix简介

    一 Zabbix简介 1.1 概述 Zabbix是一个企业级的高度集成开源监控软件,提供分布式监控解决方案.可以用来监控设备.服务等可用性和性能. 1.2 所支持监控方式 目前由zabbix提供包括但 ...

  7. Looping through the content of a file in Bash

    https://stackoverflow.com/questions/1521462/looping-through-the-content-of-a-file-in-bash One way to ...

  8. linux6.8安装docker

    Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化.容器是完全使用沙箱机制,相互之间不会有任何 ...

  9. python函数(一)调用函数

    在python中内置了很多函数或者类,比如:int,str,list,tuple,等.当然也可以自建函数,这个放在后文讨论.原理如下: 其实python中的类和方法非常非常多,这里只是以点带面,提供一 ...

  10. 洛谷 P2814 家谱(gen)

    题目背景 现代的人对于本家族血统越来越感兴趣. 题目描述 给出充足的父子关系,请你编写程序找到某个人的最早的祖先. 输入输出格式 输入格式: 输入由多行组成,首先是一系列有关父子关系的描述,其中每一组 ...