Web Socket+spring boot

创建WebSocket 类

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import javassist.tools.web.Webserver;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/** web socket
 * Created by z1761 on 2018/11/2.
 */
@ServerEndpoint(value="/websocket/{username}")
@Component
public class WebSocket {
    private static  int onlineCount = 0; //做统计使用
    private static  Map<String,WebSocket> socket = new ConcurrentHashMap<>();
    //private static CopyOnWriteArraySet<WebSocket> socket = new CopyOnWriteArraySet<>();
    private Session session;
    private String username;
    private static int count =0;

    @OnOpen
    public void onOpen(@PathParam("username")String username, Session session){
        this.username = username;
        this.session = session;
       /* count++;
        socket.put(count+"",this);*/
        addOnlineCount();
        System.out.println("已连接");
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
    }

    @OnClose
    public void onClone(@PathParam("username")String username,Session session){
        socket.remove(username);
        removeOnlineCount();
        System.out.println("断开连接");
    }

    @OnMessage
    public void onMessage(String message){
        System.out.println("来自客户端的消息:" + message);
        /*for(Map<String,WebSocket> item: socket){
            try {
               // item.onMessage();
               // item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }*/

        //sendMessageAll("给所有人");

        JSONObject json = JSONObject.parseObject(message);
        if (!json.get("TO").equals("ALL")) {
            sendMessageTo("给一个人",json.get("TO").toString());
        } else {
            sendMessageAll("给所有人");
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    //添加连接数
    public static synchronized void addOnlineCount(){
        WebSocket.onlineCount++;
    }

    // 删除连接数
    public static synchronized void removeOnlineCount(){
        WebSocket.onlineCount--;
    }

    //给你一个发消息
    public static void sendMessageTo(String message,String to){
        for (WebSocket item : socket.values()) {
            if (item.username.equals(to)) {
                item.session.getAsyncRemote().sendText(message);
            }
        }
    }

    //群发消息
    public static void sendMessageAll(String message){
        for (WebSocket item :socket.values()) {
            item.session.getAsyncRemote().sendText(message);
        }
    }

    public static synchronized Map<String,WebSocket> getClients(){
        return socket;
    }
}

创建 WebSocketConfig 类

/** 这个bean 告诉springboot 要支持websocket
 * 
 * Created by z1761 on 2018/11/5.
 */
@Component
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

pom

    <dependency>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-websocket</artifactId>
    		<version>1.3.5.RELEASE</version>
    	</dependency>
	 <dependency>
		<groupId>com.alibaba</groupId>
		<artifactId>fastjson</artifactId>
		<version>1.2.41</version>
	</dependency>

html类

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
Welcome<br/><input id="text" type="text"/>
<button onclick="send()">发送消息</button>
<hr/>
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<hr/>
<input name ="" id="user1" value="猪">
<div id="message"></div>

</body>
<script type="text/javascript">
    var websocket = null;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8080/websocket/"+"猪");
    }
    else {
        alert('当前浏览器 Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function () {
        setMessageInnerHTML("WebSocket连接发生错误");
    };

    //连接成功建立的回调方法
    websocket.onopen = function () {
        setMessageInnerHTML("WebSocket连接成功");
    }

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        setMessageInnerHTML("WebSocket连接关闭");
    }

    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }

    //发送消息
    function send() {
        //var message =
        var  shuzu ={};
        shuzu.TO = "2";
        shuzu.message = document.getElementById('text').value;

        websocket.send(JSON.stringify(shuzu));
    }
</script>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你想开发一个基于uni-app、Spring Bootsocket.io的ChatGPT聊天应用吗?这是一个很有趣的项目!下面是一些简要的步骤和建议: 1. 首先,你需要了解uni-app、Spring Bootsocket.io的基础知识。uni-app是一个跨平台的开发框架,可以用于开发iOS、Android和Web应用程序。Spring Boot是一个用于快速构建基于Spring框架的应用程序的工具。socket.io是一个实时的、双向通信的库,用于在客户端和服务器之间建立WebSocket连接。 2. 接下来,你需要确定ChatGPT的实现方式。ChatGPT是基于自然语言处理的人工智能聊天机器人,需要使用GPT模型对用户输入进行处理和回复。你可以使用已经训练好的GPT模型,也可以使用开源框架如Hugging Face Transformers来构建自己的模型。 3. 然后,你需要设计和实现前端界面。你可以使用uni-app提供的UI组件和样式来构建聊天界面。你可以使用socket.io-client库来处理客户端和服务器之间的WebSocket连接,并将用户输入发送到服务器进行处理。 4. 在后端,你需要使用Spring Boot框架来处理WebSocket连接和GPT模型。你可以使用socket.io服务器库来处理WebSocket连接,并使用Hugging Face Transformers框架来构建ChatGPT模型。当服务器接收到用户输入时,它将使用ChatGPT模型进行处理并生成回复,然后将回复发送回客户端。 5. 最后,你需要进行测试和部署。你可以使用Postman或其他工具来测试API端点和WebSocket连接。你可以将应用程序部署到云服务器或Heroku等云平台上,以便用户可以随时随地访问应用程序。 希望这些建议能帮助你开始开发ChatGPT聊天应用程序!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值