java编写的Websocket服务端

来源:互联网 发布:中文翻译文言文的软件 编辑:程序博客网 时间:2024/06/05 14:58

环境:jdk1.8

开发工具:eclipse

服务器:tomcat8.0

在tomcat8.0中,有这么一个API:F:\apache-tomcat-8.0.26\lib\websocket-api.jar,这里面有我们封装好的一些协议。

package com.lgy.websocket;import java.io.IOException;import java.util.Set;import java.util.concurrent.CopyOnWriteArraySet;import java.util.concurrent.atomic.AtomicInteger;import javax.websocket.OnClose;import javax.websocket.OnError;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;import com.lgy.util.HTMLFilter;@ServerEndpoint(value = "/chatWebsocket")public class ChatWebsocket {private static final AtomicInteger connectionIds = new AtomicInteger(0);private static final Set<ChatWebsocket> connections = new CopyOnWriteArraySet<ChatWebsocket>();private final Integer num;private Session session;public ChatWebsocket() {num = connectionIds.getAndIncrement();}// 建立连接@OnOpenpublic void start(Session session) {this.session = session;connections.add(this);System.out.println("当前连接的数量为:" + num);}//客户端关闭了连接@OnClose    public void end() {        connections.remove(this);        System.out.println("有一个断开连接,当前连接的数量为:" + num);        //broadcast(message);    }//WebSocket服务出错@OnError    public void onError(Throwable t) throws Throwable {        //log.error("Chat Error: " + t.toString(), t);System.out.println("Chat error :" + t.toString());    }//接受消息@OnMessage    public void incoming(String message) {String msg = HTMLFilter.filter(message);        System.out.println(msg);        //broadcast(filteredMessage);        broadcast(msg.toString());    }//广播public static void broadcast(String msg) {        for (ChatWebsocket client : connections) {            try {                synchronized (client) {                    client.session.getBasicRemote().sendText(msg);                }            } catch (IOException e) {                //log.debug("Chat Error: Failed to send message to client", e);                connections.remove(client);                try {                    client.session.close();                } catch (IOException e1) {                    // Ignore                }            }        }    }}

这段代码就是我们的服务端的代码。


服务端主动推送消息:

package com.lgy.controller;import java.util.HashMap;import java.util.Map;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.lgy.websocket.ChatWebsocket;@Controller@RequestMapping("/broadcast")public class BroadcastController {@RequestMapping("")@ResponseBodypublic Object Msg() {Map<String, String> msg = new HashMap<>();ChatWebsocket.broadcast("HAHAH");msg.put("msg", "服务器推送消息成功");return msg;}}


0 0
原创粉丝点击