Java Socket与Html5 websocket通信

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

一、Mysocket.java文件

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.*;

// ws://localhost:8080/ws/Tom
@ServerEndpoint("/ws/{user}")
@Component
public class MySocket {
    private String currentUser;

    //连接打开时执行
    @OnOpen
    public void onOpen(@PathParam("user") String user, Session session) {
        currentUser = user;
        System.out.println("新用户进入:" + user + ",ID:" + session.getId());
    }

    //收到消息时执行
    @OnMessage
    public String onMessage(String message, Session session) {
        System.out.println(currentUser + ":" + message);
        return currentUser + ":" + message;
    }

    //连接关闭时执行
    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        System.out.println("用户" + session.getId() + "已退出!");
    }

    //连接错误时执行
    @OnError
    public void onError(Throwable t) {
        t.printStackTrace();
    }
}

这里需要注意添加

@ServerEndpoint
@Component

二、DemoApplication.java文件

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

这里注意需要添加

@Bean
public ServerEndpointExporter serverEndpointExporter() {
    return new ServerEndpointExporter();
}

三、pom.xml需要添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-websocket</artifactId>
    <version>4.3.8.RELEASE</version>
</dependency>

四、前端

var user = 'Tom';
var baseWSUrl = 'ws://localhost:8080/ws/' + user;

if("WebSocket" in window){
    var ws = new WebSocket(baseWSUrl);

    ws.onopen = function(){
        ws.send(user + '请求连接socket!');
    }

    ws.onmessage = function(e){
        var msg = e.data;
        console.log('收到服务器发来的消息:' + msg)
    }

    ws.onclose = function(){
        console.log('关闭与服务器的连接!')
    }
}else{
    console.log('浏览器不支持websocket')
}

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

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

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

相关文章

最新文章

更多