Java Socket与Html5 websocket通信

x33g5p2x  于2022-06-27 转载在 Java  
字(2.3k)|赞(0)|评价(0)|浏览(533)

一、Mysocket.java文件

  1. import org.springframework.stereotype.Component;
  2. import javax.websocket.*;
  3. import javax.websocket.server.*;
  4. // ws://localhost:8080/ws/Tom
  5. @ServerEndpoint("/ws/{user}")
  6. @Component
  7. public class MySocket {
  8. private String currentUser;
  9. //连接打开时执行
  10. @OnOpen
  11. public void onOpen(@PathParam("user") String user, Session session) {
  12. currentUser = user;
  13. System.out.println("新用户进入:" + user + ",ID:" + session.getId());
  14. }
  15. //收到消息时执行
  16. @OnMessage
  17. public String onMessage(String message, Session session) {
  18. System.out.println(currentUser + ":" + message);
  19. return currentUser + ":" + message;
  20. }
  21. //连接关闭时执行
  22. @OnClose
  23. public void onClose(Session session, CloseReason closeReason) {
  24. System.out.println("用户" + session.getId() + "已退出!");
  25. }
  26. //连接错误时执行
  27. @OnError
  28. public void onError(Throwable t) {
  29. t.printStackTrace();
  30. }
  31. }

这里需要注意添加

  1. @ServerEndpoint
  2. @Component

二、DemoApplication.java文件

  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.web.socket.server.standard.ServerEndpointExporter;
  5. @SpringBootApplication
  6. public class DemoApplication {
  7. public static void main(String[] args) {
  8. SpringApplication.run(DemoApplication.class, args);
  9. }
  10. @Bean
  11. public ServerEndpointExporter serverEndpointExporter() {
  12. return new ServerEndpointExporter();
  13. }
  14. }

这里注意需要添加

  1. @Bean
  2. public ServerEndpointExporter serverEndpointExporter() {
  3. return new ServerEndpointExporter();
  4. }

三、pom.xml需要添加依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework</groupId>
  7. <artifactId>spring-websocket</artifactId>
  8. <version>4.3.8.RELEASE</version>
  9. </dependency>

四、前端

  1. var user = 'Tom';
  2. var baseWSUrl = 'ws://localhost:8080/ws/' + user;
  3. if("WebSocket" in window){
  4. var ws = new WebSocket(baseWSUrl);
  5. ws.onopen = function(){
  6. ws.send(user + '请求连接socket!');
  7. }
  8. ws.onmessage = function(e){
  9. var msg = e.data;
  10. console.log('收到服务器发来的消息:' + msg)
  11. }
  12. ws.onclose = function(){
  13. console.log('关闭与服务器的连接!')
  14. }
  15. }else{
  16. console.log('浏览器不支持websocket')
  17. }

五、编写工程中碰到过的问题

问题:WebSocket connection to ‘ws://localhost:8080/ws/Tom’ failed: Error during WebSocket handshake: Unexpected response code: 404

这个需要添加上边那个@Bean和@Component的代码

相关文章

最新文章

更多