HTTP与websocket协议区别
HTTP协议的特点
- 1.无状态协议
- 2.用于通过Internet发送请求消息和响应消息
- 3.使用端口接收和发送消息,默认端口80
缺点:无法直接实现双向通信与消息推送
WebSocket:
是HTML5开始提供的一种浏览器与服务器间进行全双工通讯的网络技术。依靠这种技术可以实现客户端和服务器端的长连接,双向实时通信。
特点:
- 1.事件驱动
- 2.异步
- 3.使用ws或者wss协议的客户端socket
缺点:
少部分浏览器不支持,浏览器支持的程度与方式有区别。
1.应用控制层:
@SpringBootApplication
@RestController
public class WebSocketChatApplication {
/**
* 登陆界面
*/
@GetMapping("/")
public ModelAndView login() {
return new ModelAndView("/login");
}
/**WebSecurityConfigurerAdapter
* 聊天界面
*/
@GetMapping("/index")
public ModelAndView index(String username, String password, HttpServletRequest request) throws UnknownHostException {
if (StringUtils.isEmpty(username)) {
username = "匿名用户";
}
ModelAndView mav = new ModelAndView("/chat");
mav.addObject("username", username);
// webSocketUrl -> ws://ip地址:8080/chat
mav.addObject("webSocketUrl", "ws://"+InetAddress.getLocalHost().getHostAddress()+":"+request.getServerPort()+request.getContextPath()+"/chat");
return mav;
}
public static void main(String[] args) {
SpringApplication.run(WebSocketChatApplication.class, args);
}
}
2.WebSocket服务端
同步方式阻塞式:推送消息给每个会话
/**
* WebSocket 聊天服务端
*