首页>代码>spring mvc基于webSocket实现用户聊天通信的一个小demo>/websocket/src/main/java/org/xdemo/example/websocket/controller/MsgController.java
package org.xdemo.example.websocket.controller;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.socket.TextMessage;
import org.xdemo.example.websocket.entity.Message;
import org.xdemo.example.websocket.entity.User;
import org.xdemo.example.websocket.websocket.MyWebSocketHandler;
import com.google.gson.GsonBuilder;
@Controller
@RequestMapping("/msg")
public class MsgController {
@Resource
MyWebSocketHandler handler;
Map<Long, User> users = new HashMap<Long, User>();
// 模拟一些数据
@ModelAttribute
public void setReqAndRes() {
User u1 = new User();
u1.setId(1L);
u1.setName("张三");
users.put(u1.getId(), u1);
User u2 = new User();
u2.setId(2L);
u2.setName("李四");
users.put(u2.getId(), u2);
}
// 用户登录
@RequestMapping(value = "login", method = RequestMethod.POST)
public ModelAndView doLogin(User user, HttpServletRequest request) {
request.getSession().setAttribute("uid", user.getId());
request.getSession().setAttribute("name", users.get(user.getId()).getName());
return new ModelAndView("redirect:talk");
}
// 跳转到交谈聊天页面
@RequestMapping(value = "talk", method = RequestMethod.GET)
public ModelAndView talk() {
return new ModelAndView("talk");
}
// 跳转到发布广播页面
@RequestMapping(value = "broadcast", method = RequestMethod.GET)
public ModelAndView broadcast() {
return new ModelAndView("broadcast");
}
// 发布系统广播(群发)
@ResponseBody
@RequestMapping(value = "broadcast", method = RequestMethod.POST)
public void broadcast(String text) throws IOException {
Message msg = new Message();
msg.setDate(new Date());
msg.setFrom(-1L);
msg.setFromName("系统广播");
msg.setTo(0L);
msg.setText(text);
handler.broadcast(new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(msg)));
}
}
最近下载更多
yuanshun LV7
2023年6月2日
人工智能4708 LV11
2023年5月8日
ewan007 LV30
2023年4月21日
lironggang LV38
2023年2月16日
136542892@qq.com LV23
2022年6月20日
Wave666 LV6
2022年3月21日
15380502522 LV2
2021年6月30日
lris_luanling LV11
2021年4月21日
a1677596408 LV23
2021年4月15日
宋国斌 LV4
2021年3月17日
最近浏览更多
3334004690 LV11
2024年5月28日
Luck_ZDM LV12
2024年5月22日
Xiaobaiya11 LV2
2024年3月4日
yhwyhw1 LV2
2023年12月21日
小新Coding LV9
2023年9月7日
微信网友_6627705560322048 LV1
2023年8月30日
wanfeng_233 LV4
2023年8月29日
你好啊呐 LV19
2023年8月23日
yuanshun LV7
2023年6月2日
tianli3000 LV8
2023年5月15日

