【Websocket】实现聊天室上传照片

1、ChatServer

@Slf4j
@ServerEndpoint("/websocket")
@Component
public class ChatServer {
    @OnOpen
    public void onOpen(){
        log.info("---------------------------->on Open");
    }

    @OnClose
    public void OnClose(){
        log.info("---------------------------->on Close");
    }

    @OnMessage
    @SneakyThrows
    public void onMessage(String message, Session session){
        log.info("------------------->message:{}",message);
        for (Session se:session.getOpenSessions()){
            //把消息转发到其他用户
            se.getBasicRemote().sendText(message);
        }
    }
}

2、启动类的修改

因为我们图片采用base64发送,因此内容肯定会很长,有的小的图片可以发(比如1-2k这种)

但大的就不行。于是就顺着websocket发送内容太长了如何解决的问题
即加入配置 在原来的启动类中实现ServletContextInitializer接口并设置发送内容大小限制。

@SpringBootApplication
public class XiyuemallChatApplication implements ServletContextInitializer {

    public static void main(String[] args) {
        SpringApplication.run(XiyuemallChatApplication.class, args);
    }
    //添加websocket支持
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){

        return new ServerEndpointExporter();
    }

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
     servletContext.setInitParameter("org.apache.tomcat.websocket.textBufferSize","1024000");
    }
}

前端页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>websocket测试</title>
</head>
<body>
<input type="text" id="text"><button onclick="sendText()">发送</button>
<input type="file" id="f" onchange="chooseFile()">
<div id="main">
</div>

<script type="text/javascript">
    var ws = new WebSocket('ws://localhost:8989/websocket');
    ws.onopen = function (ev) {
        console.log("------连接服务器成功-----")
    }

    ws.onerror=function (ev) {
        console.log("------连接服务器出错-----")
    }

    //监听 接收消息
    ws.onmessage=function (ev) {
        //解析json
        var json = JSON.parse(ev.data);
        //1为文本消息
        if(json.code==1){
            document.querySelector("#main").innerHTML="<p>"+json.msg+"</p>"+document.querySelector("#main").innerHTML;
            //2为图片消息
        }else if(json.code==2){
            document.querySelector("#main").innerHTML='<img width="150px" src='+json.msg+'>'+document.querySelector("#main").innerHTML;
        }
    }

    //发送文本消息
    function sendText() {
        var msg = document.querySelector("#text").value
        if(msg){
            //websocket发送文本消息
            ws.send(JSON.stringify({code:1,msg:msg}));
            document.querySelector("#text").value=""
        }
    }

    //发送图片消息
    function chooseFile() {
        var files = document.querySelector("#f").files
        if(files.length>0){
            var fileReader = new FileReader();
            fileReader.readAsDataURL(files[0])
            fileReader.onload=function (e) {
                var s = JSON.stringify({code:2,msg:e.target.result});
                //websocket发送图片消息
                ws.send(s)
            }
        }
    }
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/kanseu/article/details/123767357#comments_24454378