websocket前端以1M/s的速度发送数据给后端 10C





远远超过传输数据的大小 肯定回堵塞的 建议拆分发送 控制大小 发送数据的时候还要查询通道的数据是否推送出去了

websocket 服务端缓冲区满了 就会断开链接
ReceiveBufferSize = 64 * 1024, //用于接收数据的缓冲区大小,默认为2048。


Csdn user default icon
Gorilla WebSocket与golang.org/x/net/websocket的比较

<div class="post-text" itemprop="text"> <p>According <a href="https://github.com/gorilla/websocket#gorilla-websocket-compared-with-other-packages" rel="nofollow">Gorilla Websockets Project</a> it is not possible to send pings and pongs using <strong>golang.org/x/net/websocket</strong>. At the same time, the following is on the project page of <a href="http://godoc.org/golang.org/x/net/websocket" rel="nofollow">golang.org/x/net/websocket</a>:</p> <blockquote> <p>Package websocket implements a client and server for the WebSocket protocol as specified in RFC 6455.</p> </blockquote> <p>I am a little confused. <strong>golang.org/x/net/websocket</strong> implements RFC 6455 but can not send control frames (cancel, ping, pong) although this is specified in <a href="http://tools.ietf.org/html/rfc6455#section-5.5" rel="nofollow">RFC 6455 - Section Control Frames</a></p> <p>So what will happen if I use <strong>golang.org/x/net/websocket</strong> package. Will the connection abort after a timeout? In other words, how is it ensured here that the connection does not break off.</p> </div>

此websocket网址“ ws:// {{$}} / ws”是什么意思?

<div class="post-text" itemprop="text"> <p>I work with websocket in go. And I got a websocket url format from a trivial example that I google like this:</p> <pre><code>ws://{{$}}/ws </code></pre> <p>Relatively complete code below:</p> <p>home.html:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Chat Example&lt;/title&gt; &lt;script type="text/javascript"&gt; $(function() { ...... if (window["WebSocket"]) { conn = new WebSocket("ws://{{$}}/ws"); conn.onclose = function(evt) { appendLog($("&lt;div&gt;&lt;b&gt;Connection closed.&lt;/b&gt;&lt;/div&gt;")) } conn.onmessage = function(evt) { appendLog($("&lt;div/&gt;").text(evt.data)) } } else { appendLog($("&lt;div&gt;&lt;b&gt;Your browser does not support WebSockets.&lt;/b&gt;&lt;/div&gt;")) } ...... }); &lt;/script&gt; &lt;/head&gt; &lt;/html&gt; </code></pre> <p>And wsServer.go:</p> <pre><code>package main import ( "flag" "log" "net/http" "text/template" ) var addr = flag.String("addr", ":8080", "http service address") var homeTempl = template.Must(template.ParseFiles("home.html")) func serveHome(w http.ResponseWriter, r *http.Request) { ...... w.Header().Set("Content-Type", "text/html; charset=utf-8") homeTempl.Execute(w, r.Host) } func main() { http.HandleFunc("/", serveHome) http.HandleFunc("/ws", serveWs) err := http.ListenAndServe(:8080, nil) if err != nil { log.Fatal("ListenAndServe: ", err) } } </code></pre> <p>I thought it would be a regular expression while actually I can't explain it.</p> <p>I test it on my own PC browser, and connect success with:</p> <pre><code>http://localhost:8080 </code></pre> <p>but </p> <pre><code>http://ip:8080 (which ip is my computer's also the litsening server's ip) </code></pre> <p>not. And why? </p> <p>Of course it works when I change "ws://{{$}}/ws" to a certain url. But I want to know why?And what can this expression matching for?</p> <p>The complete example code is large, I think above is enough to the question. If I miss something you can find out complete example in this page : <a href="https://github.com/garyburd/go-websocket/tree/master/examples/chat" rel="nofollow">https://github.com/garyburd/go-websocket/tree/master/examples/chat</a></p> </div>

如何使用Go和gorilla websocket仅发送给一个客户端,而不是所有客户端

<div class="post-text" itemprop="text"> <p>I am trying to learn websockets with Go. I have been looking at examples with gorilla websocket.</p> <p>I have checked out these 2 examples that show how to use gorilla websocket:</p> <p><a href="https://github.com/gorilla/websocket/tree/master/examples" rel="nofollow">https://github.com/gorilla/websocket/tree/master/examples</a></p> <p><a href="https://www.youtube.com/watch?v=ysAZ_oqPOo0" rel="nofollow">https://www.youtube.com/watch?v=ysAZ_oqPOo0</a></p> <p>All of these examples show how to connect to a websocket server, send and receive texts. But what I don't understand is how you can send to only one client. Because in a real world application you will have users, and we don't want all users to receive the same message and same data. Is there a way for me to get the unique id of a connection which I can save in a database like redis and link it to a user id in the same database, and then use that websocket id to send back to a specific client if that user id received a message or a notification? Is this how one would go about and achieve something like this? If that is the case, how would I that?</p> </div>

Gorilla Websocket如何将二进制数据解组为JSON?

<div class="post-text" itemprop="text"> <p>I'm following the <a href="https://github.com/gorilla/websocket/tree/master/examples/chat" rel="nofollow noreferrer">chat example</a> provided by gorilla.</p> <p>I still can get to unmarshal the json data sent. Should I do this in the <code>readPump()</code>:</p> <pre><code>func (c *ChatClient) readPump() { defer func() { c.hub.unregisterChan &lt;- c c.conn.Close() }() c.conn.SetReadLimit(maxMessageSize) c.conn.SetReadDeadline(time.Now().Add(pongWait)) c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil }) for { _, message, err := c.conn.ReadMessage() // =================MY CODE START============= var comment Comment err = c.conn.ReadJSON(comment) if err != nil { LogErr("readjson()", err) break } err = json.Unmarshal(message, comment) if err != nil { LogErr("readjson()", err) break } // =================MY CODE END============= if err != nil { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) { LogErr("IsUnexpectedCloseError()", err) } break } message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1)) c.hub.broadcastChan &lt;- message } } </code></pre> <p>or in the <code>writePump()</code></p> <pre><code>func (c *ChatClient) writePump() { ticker := time.NewTicker(pingPeriod) defer func() { ticker.Stop() c.conn.Close() }() for { select { case message, ok := &lt;-c.send: c.conn.SetWriteDeadline(time.Now().Add(writeWait)) // CLOSE if !ok { c.conn.WriteMessage(websocket.CloseMessage, []byte{}) return } w, err := c.conn.NextWriter(websocket.BinaryMessage) if err != nil { LogErr("c.conn.NextWriter", err) return } w.Write(message) // Add queued chat messages to the current websocket message. n := len(c.send) for i := 0; i &lt; n; i++ { w.Write(newline) w.Write(&lt;-c.send) } if err := w.Close(); err != nil { LogErr("w.Close()", err) return } case &lt;-ticker.C: c.conn.SetWriteDeadline(time.Now().Add(writeWait)) if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil { LogErr("c.conn.WriteMessage()", err) return } } } } </code></pre> <p>The LogErr() methods don't print any message. Totally lost here.</p> </div>


自己网上找了一个例子,在服务端,我只发送字符串给客户端的时候是正常的,但是当在字符串前面添加int16和int32一起发送回给客户端就报错了:WebSocket connection to 'ws://' failed: One or more reserved bits are on: reserved1 = 1, reserved2 = 0, reserved3 = 1 客户端可以正确读取到前面的两个int数据 但是后面的字符串读取数据不全,而且客户端还报错。求大神帮忙解答下。非常感谢。 https://pan.baidu.com/s/1i7kZy8t 源码地址

Websocket消息发送到特定房间-Golang Kataras / Iris

<div class="post-text" itemprop="text"> <p>I am trying to send Message to Particular Room, but it doesn't work and It sends message to all room along with my message being received twice from my name and with first chat room user name. Message from 1 Room is broadcasted to all Chat Room.</p> <p>I have used Example Code from here- <a href="https://github.com/kataras/iris/blob/master/_examples/websocket/secure/main.go" rel="nofollow noreferrer">https://github.com/kataras/iris/blob/master/_examples/websocket/secure/main.go</a>. and <a href="https://github.com/kataras/iris/blob/master/_examples/websocket/native-messages/main.go" rel="nofollow noreferrer">https://github.com/kataras/iris/blob/master/_examples/websocket/native-messages/main.go</a></p> <p>Below is the Code, I am using, that is giving me the error :</p> <pre><code> var myChatRoom = strconv.Itoa(room.ID) ws := websocket.New(websocket.Config{}) ws.OnConnection(func(c websocket.Connection) { c.Join(myChatRoom) c.To(myChatRoom).EmitMessage([]byte(user.(users).Username + " has Joined Chat!")) c.OnMessage(func(data []byte) { message := string(data) if message == "leave" { c.Leave(myChatRoom) c.To(myChatRoom).EmitMessage([]byte(user.(users).Username + " has Left Chat!")) return } c.To(myChatRoom).EmitMessage([]byte(user.(users).Username + ": " + message)) }) c.OnDisconnect(func() { fmt.Printf("Connection with ID: %s has been disconnected! ", c.ID()) }) }) </code></pre> <p>HTML Code:</p> <pre><code>&lt;div id="messages" style="border-width: 1px; border-style: solid; height: 200px;overflow:auto"&gt;&lt;/div&gt; &lt;input type="text" id="messageTxt" /&gt; &lt;button type="button" id="sendBtn"&gt;Send&lt;/button&gt; </code></pre> <p>Javascript Code:</p> <pre><code>&lt;script&gt; var messageTxt; var messages; var HOST = 'localhost' jQuery(function() { messageTxt = jQuery("#messageTxt"); messages = jQuery("#messages"); w = new WebSocket("ws://" + HOST + "/my_endpoint"); w.onopen = function() { console.log("Websocket connection enstablished"); }; w.onclose = function() { appendMessage(jQuery("&lt;div&gt;&lt;center&gt;&lt;h3&gt;Disconnected&lt;/h3&gt;&lt;/center&gt;&lt;/div&gt;")); }; w.onmessage = function(message) { console.log("Message Appended: " + message) appendMessage(jQuery("&lt;div&gt;" + message.data + "&lt;/div&gt;")); }; jQuery("#sendBtn").click(function() { w.send(messageTxt.val().toString()); messageTxt.val(""); }); }) function appendMessage(messageDiv) { messageDiv.appendTo(jQuery("#messages")); } &lt;/script&gt; </code></pre> <p><strong>Error:</strong></p> <ol> <li><p>It sends message to all ROOM and not specific Room.</p></li> <li><p>User who created room first automatically joins all the ROOM</p></li> <li><p>People sending message in other ROOM see their message being Repeated/cloned in their ROOM by "FirstUser" who created first room in chat. (Irrespective of whether he is member of the chat group or not)</p></li> </ol> <p><strong>Expecting:</strong></p> <ol> <li><p>People can send/receive message to only those room where they have joined.</p></li> <li><p>First User should not be able to join CHATRoom automatically.</p></li> <li><p>People should not see their message being repeated again with "FirstUser" name.</p></li> </ol> </div>

android- websocket连接“wss://ws.biki.com/kline-api/ws”时执行onOpen,但是send信息后没有返回值

//用的websocket版本: implementation "org.java-websocket:Java-WebSocket:1.4.0" String url = "wss://ws.biki.com/kline-api/ws"; WebSocketClient client = new WebSocketClient(new URI(url), new Draft_6455()); //发送订阅 服务端返回信息 client.send("{ \"event\": \"sub\", \"params\": { \"channel\": \"market_btcusdt_kline_1min\", \"cb_id\": \"aaaa\" } }");



GO Websocket向所有客户发送消息

<div class="post-text" itemprop="text"> <p>Everything works fine with this code (shortened it for better reading).</p> <p>When <code>Client1</code> sends a request to the Server, the Server responses to him instantly. But, the other clients can not see the response message.</p> <p>So I want to make it go further: When a client sends a request to the server, the server will response to all clients so that all clients can see the message.</p> <p>How can I do that? Any examples or nice tutorials for beginners?</p> <p>Thanks in advance!</p> <p>Server:</p> <pre><code>import ( "github.com/gorilla/websocket" ) func main() { http.Handle("/server", websocket.Handler(echoHandler)) } func echoHandler(ws *websocket.Conn) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { return } for { messageType, p, err := conn.ReadMessage() if err != nil { return } print_binary(p) // simple print of the message err = conn.WriteMessage(messageType, p); if err != nil { return } } } </code></pre> </div>


websocket客户端一发送ping/pong消息连接就关闭,服务端一发送ping消息客户端就执行onError函数。我客户端发送的方式为: ``` client.send(new byte[]{(byte)0x89, (byte)0x00});ping client.send(new byte[]{(byte)0x8A, (byte)0x00});pong ``` 服务端直接发送的spring中的PingMessage


前端 let wsuri= global.wsURL+"/slims/v1/websocket/"; if ("WebSocket" in window) { console.log("您的浏览器支持查看在线人数") } else { alert('当前浏览器不支持查看人员在线状态'); } this.websockt = new WebSocket(wsuri); this.websockt.onmessage = this.websocketonmessage; this.websockt.onerror = this.websocketonerror; this.websockt.onclose = this.websocketclose; this.websockt.onopen =this.websocketonopen; // Web Socket 已连接上,使用 send() 方法发送数据s console.log('数据发送中...') this.websockt.send('Holle') console.log('数据发送完成') } this.websockt.send = this.websocketsend; }, websocketonopen(){ //连接建立之后执行send方法发送数据 console.log("xxxx"); }, websocketonerror(){//连接建立失败重连 console.log("重新连接") this.initWebSocket(); }, websocketonmessage(e){ //数据接收 console.log("数据接收") }, websocketsend(Data){//数据发送 console.log("数据发送"); this.websockt .send("幸福9999");debugger alert(8888); }, websocketclose(e){//关闭连接 console.log("关闭连接") this.websockt.onclose(); }, }, 后台 : @OnOpen public void onOpen(Session session, EndpointConfig sce) throws IOException { this.session = session; //Object转换成Long Long uuid = Long.valueOf(String.valueOf(sce.getUserProperties().get("uuid"))); if (null == uuid) { onClose(); } webSocketSet.add(this); //线程安全的原子数+1 subOnlineCount(); System.out.println("有链接加入,当前人数为:" + getOnline_num()); this.session.getAsyncRemote().sendText("有链接加入,当前人数为:" + getOnline_num()); map.put(session, uuid); System.out.println("当前登录人uid" + uuid); String stats = "0"; //是首次登陆的人 if (0 == userSocketService.list(Condition.create().eq("uid", uuid)).size()) { UserSocket usersocket = new UserSocket(); usersocket.setUid(uuid); usersocket.setStats(stats); usersocket.setCompany_id(0L); userSocketService.saves(usersocket); } else { UserSocket usersocket = new UserSocket(); usersocket.setUid(uuid); usersocket.setStats("0"); userSocketService.update(usersocket, Condition.create().eq("uid", uuid)); } sendMessage("------------------------后台-----) 可以连接上,但是没法发消息,正常这里应该显示状态码是101的,但是一直显示在链接中明明后台已经收到请求了,到底是怎么回事呢? ![图片说明](https://img-ask.csdn.net/upload/201810/17/1539757022_269768.png)

java WebSocket 相关 前端已经接收到值了,为什么后台代码还是会出异常呀

java Web Socket 初学者 最近遇到了一个问题 ,就是在后台向前端推送数据时前台页面明明接收到了值,但是后台代码还是会出异常这是为什么! 下面是我写的代码 这个是主线程代码 ``` package test; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; public class ChatServer { // 记录所有客户端的Socket public static List<Socket> clientSocket = new ArrayList<Socket>(); public ChatServer() throws Exception { // 创建ServerSocket,准备接受客户端连接 ServerSocket ss = new ServerSocket(30000); while (true) { System.out.println(clientSocket.size()); // 接收客户端连接 Socket socket = ss.accept(); // 将客户端Socket添加到clientSocket集合中 clientSocket.add(socket); // 启动线程 new ServerThread(socket).start(); } } public static void main(String[] args) throws Exception { new ChatServer(); } } ``` 下面是线程内代码 ``` package test; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.security.MessageDigest; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; import sun.misc.BASE64Encoder; public class ServerThread extends Thread{ private Socket socket; public ServerThread(Socket socket) { this.socket = socket; } private int as = 0; @SuppressWarnings("finally") public void run() { System.out.println("为用户:" + socket.getInetAddress().getHostName() + "开启线程"); try { // 得到Socket对应的输入流 InputStream is = socket.getInputStream(); // 得到Socket对应的输出流 OutputStream out = socket.getOutputStream(); byte[] buff = new byte[1024]; String req = ""; // 读取数据,此时建立与wabSocket的握手 int count = is.read(buff); // 如果读取的数据长度>0 if (count > 0) { // 将读取的数据转化为字符串 req = new String(buff, 0, count); // System.out.println("握手请求:" + req);// req = 客户端信息 // 获取WebSocket的值 String seckey = getSecWebSocketKey(req); String response = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: " + "websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: " + getSecWebSocketAccept(seckey) + "\r\n\r\n"; System.out.println("secAccept = " + getSecWebSocketAccept(seckey)); //推送客户端 out.write(response.getBytes("utf-8")); int hasRedad = 0; // 不断读取WebSocket发送过来的数据 System.out.println("while循环前,等待前端推送数据。。。。。。。。。。。。"); while ((hasRedad = is.read(buff)) > 0) { //必须这么写 System.out.println("接收到客户端" + socket.getInetAddress().getHostName() + "字节数:" + hasRedad); /* * 因为WebSocket发送过来的数据遁寻了一定的协议格式, 其中第3~6个字节是数据掩码, * 从第七个字节开始才是真正的有效数据。 因此程序使用第3~6个字节对后面的数据进行了处理 */ for (int i = 0; i < hasRedad - 6; i++) { buff[i+6] = (byte)(buff[i%4+2]^ buff[i+6]); } //获得从浏览器发送过来的数据 String pushMsg = new String(buff, 6, hasRedad-6, "utf-8"); //遍历Socket集合,依次向每个Socket发送数据 int a=1; for(Iterator<Socket> it = ChatServer.clientSocket.iterator();it.hasNext();){ //获得集合中的Socket对象 System.out.println("Socket集合中有:"+ChatServer.clientSocket.size()+"个对象等待发送信息"); Socket s = it.next(); //发送数据时,第一个字节必须与读到的第一个字节相同 byte[] pushHead = new byte[2]; pushHead[0] = buff[0]; //发送数据时,第二个字节记录 发送数据的长度 pushHead[1] = (byte)pushMsg.getBytes("utf-8").length; try { System.out.println("web推送前"); System.out.println("Socket 的InputStream值:"+is.available()); System.out.println("web推送中........"); //发送前两个字节 s.getOutputStream().write(pushHead); //发送有效数据 s.getOutputStream().write(pushMsg.getBytes("utf-8")); } catch (Exception e) { System.out.println("向前端推送数据后发生了异常"); e.printStackTrace(); }finally{ //如果s.getInputStream().available() == 0,表明该Scoket已经关闭 //将该Socket从Socket集合中删除 System.out.println("从集合中删除该Socket对象"); ChatServer.clientSocket.remove(s); a=2; break; } } System.out.println("WEB 推送后"); if(a==2){ break; } } } } catch (Exception e) { System.out.println("有一个Socket对象关闭了,该对象线程结束"); }finally{ try { //关闭Socket System.out.println("关闭该Socket对象"); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // 获取WebSocket请求的Seckey private String getSecWebSocketKey(String req) { // 构建正则表达式,获取Sec-WebSocket-Key:后面的内容 Pattern p = Pattern.compile("^(Sec-WebSocket-Key:).+",Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); Matcher m = p.matcher(req); if (m.find()) { // 提取Sec-WebSocket-Key String foundstring = m.group(); return foundstring.split(":")[1].trim(); } else { return null; } } // 根据WebSocket请求的Seckey计算SecAccept private String getSecWebSocketAccept(String key) throws Exception { String guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; key += guid; MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(key.getBytes("ISO-8859-1"), 0, key.length()); byte[] shalHash = md.digest(); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(shalHash); } } ``` 没有错误信息,不报错的 但是就是程序走不了了

vue前端websocket连接不上springboot,报错Connection closed before receiving a handshake response

搞定了,我的代码写的基本没有问题,毕竟都是按着教程一步一步来的,主要问题在于,我的开发环境和教程不一致,我是前后端分离,请求8080即请求的前端项目,当然会超时然后建立连接失败。我查看了一下前后端各自的端口:前端8080,后端63000,然后把 ``` this.sock = new WebSocket("ws:localhost:8080/websocket");//建立连接 ``` 改成 ``` this.sock = new WebSocket("ws:localhost:63000/websocket");//建立连接 ``` 就可以了,换成后端的端口号。 --- 以下是原问题 --- 照着网上的教程写的例子,整合到自己的项目中。前端用vue写的,js里几乎和教程一模一样,主要问题在于 ``` this.sock = new WebSocket("ws:localhost:8080/websocket");//建立连接 ``` --- **创建的websocket内的方法都是null,如图:** ![图片说明](https://img-ask.csdn.net/upload/201909/24/1569293600_266157.png) --- **然后观察控制台内过了一段时间报错,提示:** ``` WebSocket connection to 'ws://localhost:8080/websocket' failed: Connection closed before receiving a handshake response ``` --- **控制台错误详情见图:** ![图片说明](https://img-ask.csdn.net/upload/201909/24/1569294057_247788.png) --- **前端代码:** ``` webSocket() { debugger; // 建立socket连接 if ('WebSocket' in window) {//判断当前浏览器是否支持webSocket // this.sock = new WebSocket("ws:localhost:8080/bootTest/websocket");//建立连接(带后端项目名) this.sock = new WebSocket("ws:localhost:8080/websocket");//建立连接(不带后端项目名) } else { alert('你的浏览器暂不支持websocket :('); } var sock = this.sock; console.log(sock); sock.onopen = function (e) {//成功建立连接 console.log(e); }; sock.onmessage = function (e) {//接收到消息 console.log(e) $(".message").append("<p><font color='red'>"+e.data+"</font>") }; sock.onerror = function (e) {//连接发生错误 console.log(e); }; sock.onclose = function (e) {//连接关闭 console.log(e); }; ////监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function(){ websocket.close(); }; } ``` --- --- --- --- 后端代码: ``` import java.io.IOException; import java.util.concurrent.CopyOnWriteArraySet; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import javax.websocket.*; import lombok.extern.slf4j.Slf4j; @Slf4j @ServerEndpoint("/websocket") public class WebSocketServer { //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 private static int onlineCount = 0; //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。 private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>(); //与某个客户端的连接会话,需要通过它来给客户端发送数据 private Session session; /** * 连接建立成功调用的方法*/ @OnOpen public void onOpen(Session session) { this.session = session; webSocketSet.add(this); //加入set中 addOnlineCount(); //在线数加1 log.info("有新连接加入!当前在线人数为" + getOnlineCount()); try { sendMessage("连接成功"); } catch (IOException e) { log.error("websocket IO异常"); } } // //连接打开时执行 // @OnOpen // public void onOpen(@PathParam("user") String user, Session session) { // currentUser = user; // System.out.println("Connected ... " + session.getId()); // } /** * 连接关闭调用的方法 */ @OnClose public void onClose() { webSocketSet.remove(this); //从set中删除 subOnlineCount(); //在线数减1 log.info("有一连接关闭!当前在线人数为" + getOnlineCount()); } /** * 收到客户端消息后调用的方法 * @param message 客户端发送过来的消息 */ @OnMessage public void onMessage(String message, Session session) { log.info("来自客户端的消息:" + message); //群发消息 for (WebSocketServer item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { e.printStackTrace(); } } } /** * 发生错误 * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { log.error("发生错误"); error.printStackTrace(); } public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } /** * 群发自定义消息 * */ public static void sendInfo(String message) throws IOException { log.info(message); for (WebSocketServer item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { continue; } } } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { WebSocketServer.onlineCount++; } public static synchronized void subOnlineCount() { WebSocketServer.onlineCount--; } } ```


1.现有多个线程查询不同的设备获取不同的数据。 2.当网页打开后自动产生一个websocket连接。 上面12两点已经完成,但是现在对我来说查询线程和websocket它们相互独立,怎么才能在查询线程中调用websocket的send方法把数据传到前台网页呢。


<div class="post-text" itemprop="text"> <p>I want to send close code to client, but It is always 1006.</p> <p>I tried,</p> <pre><code>func ServeWs(w http.ResponseWriter, r *http.Request) { conn := Upgrade(w, r) msg := websocket.FormatCloseMessage(4001, "myError") // case 1 conn.WriteMessage(websocket.CloseMessage, msg) // case 2 //conn.WriteControl(websocket.CloseMessage, msg, time.Now().Add(time.Second)) // case 3 //w, err := conn.NextWriter(websocket.CloseMessage) //if err != nil { // return //} //if _, err = w.Write(msg); err != nil { // log.Println(err) //} //w.Close() time.Sleep(10*time.Second) conn.Close() } func Upgrade(w http.ResponseWriter, r *http.Request) *websocket.Conn{ conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println(err) return nil } return conn } </code></pre> <p>But Not worked all these cases. How can I send except 1006 to client?</p> <p>I also tested Node js ws package to verify client's. </p> <pre><code>const WebSocket = require('ws'); const ws = new WebSocket.Server({ port: 8088 }); ws.on('connection', function connection(ws) { ws.close(1000, 'bac'); }); </code></pre> <p>This javascript codes worked fine.</p> <p>=== Added ===</p> <p>Client Codes for testing. In chrome dev tool console, paste below</p> <pre><code>conn = new WebSocket("ws://"); conn.onclose = function(evt){console.log("do", evt);}; conn.onerror = function(err){console.log("err", err);}; conn.onmessage = function(msg){console.log("msg", msg);}; </code></pre> </div>


后端实时获取类似json格式的数据,获取后进行处理,传向前端页面,前端可以实时显示处理后的数据? 举个例子 1. 后端每隔一短时间后就会获取到传感器的温度等数据,然后进行数据解析,前端会实时获取到来自后端所处理的数据。 1. 例如我们电脑CPU的实时数据显示,我们可以清楚的看CPU的变化。 请问各位大佬,这个应该怎么做? 有什么思路么?


<div class="post-text" itemprop="text"> <p>I'm naively use <a href="https://github.com/kaihendry/WebSocketHook/blob/master/server/main.go#L22">_, err := ws.Read(msg)</a> to keep a Web socket open in my code. I don't think it works reliably.</p> <p>In other code I've noticed people doing a <a href="https://github.com/skarnecki/gotail/blob/master/app.go#L56">sleep loop</a>. What's the correct way to keep a Web socket open &amp; stable? I assume the underlying library does ping/pongs?</p> <p>Update: I'm pretty confident that the <a href="https://github.com/kaihendry/WebSocketHook/blob/fd3fc976bf1ce5865b48005e3d4024682a1c9533/client/client.go">client.go</a> is to blame since it doesn't seem to redial after a disconnect is seen on the server. I made <a href="https://youtu.be/hmOI3MIIXIM">a video demonstrating the issue</a>.</p> </div>

与“ws:// localhost:8080 /”的WebSocket连接失败:这个报错是怎么回事?

我的客户端脚本和服务器之间没有WebSocket连接,它在我当前的环境中运行得很好。同时,我也遵循这个<a href="http://socketo.me/docs/push" rel="nofollow noreferrer">链接</a>。 下面是一个服务器脚本,它初始化WebSocket服务器并让客户端连接到了8080端口。</p> <pre><code>public function run() { $loop = Factory::create(); $pusher = new Pusher; $context = new Context($loop); $pull = $context-&gt;getSocket(ZMQ::SOCKET_PULL); $pull-&gt;bind('tcp://'); // Binding to means the only client that can connect is itself $pull-&gt;on('message', array($pusher, 'onBlogEntry')); // Set up our WebSocket server for clients wanting real-time updates $webSock = new Server('', $loop); // Binding to means remotes can connect $webServer = new IoServer( new HttpServer( new WsServer( new WampServer( $pusher ) ) ), $webSock ); $loop-&gt;run(); </code></pre> <p>这是客户端脚本:</p> <pre><code>var conn = new ab.Session('ws://localhost:8080', function() { /* subscribe to following topics */ conn.subscribe('new_order', function(topic, data) .. </code></pre> <p>同样,这在本地设置中运行良好。</p> <p>还要注意的是,我的应用程序是使用来自docker容器的指定端口承载的。</p> <pre><code> </code></pre> <p>我还尝试在客户端脚本中指定IP:</p> <pre><code>var conn = new ab.Session('ws://', function() { /* subscribe to following topics */ conn.subscribe('new_order', function(topic, data) ... </code></pre> <p>在这种情况下,我会得到以下错误:</p> <pre><code>WebSocket connection to 'ws://' failed: Error during WebSocket handshake: Unexpected response code: 403 </code></pre> <p>这里缺少什么?</p> </div>

Secure WebSocket(wss://)在Firefox上不起作用

<div class="post-text" itemprop="text"> <p>I have a working WebSocket non secure application. But my website uses https and I need a Secure WebSocket connection to avoid Firefox to complain about the fact that the connection is insecure.</p> <p>I am using <a href="http://code.google.com/p/php-websocket-server/">php-websocket-server</a> for my WebSocket server with PhP 5.2.9, so when i use WebSocket secure i can't decrypt packets with the openssl_decrypt function. </p> <p>That's why i used <a href="http://www.stunnel.org/">stunnel</a> in order to decrypt packets sent by the client using wss, to do that i binded client WebSocket to 12345 port an server WebSocket to 54321 port, then i added a stunnel in server mode :</p> <pre><code>[wsServer] accept = 12345 connect = </code></pre> <p>With this configuration my application works fine on Chrome through https + wss. But on Firefox there's a problem during the handshake, it seems that <code>Sec-WebSocket-Version</code> and <code>Sec-WebSocket-Key</code> are missing in the header. I don't understand because it works on Firefox through http + ws.</p> <p>Thanks in advance for your help.</p> <p>Edit : i added an exception for the certificate on the port 12345, now the handshake is going well because i think Firefox now have the <code>Sec-WebSocket-Key</code>.</p> <p>Here the working header request with Firefox (bigger than Chrome request):</p> <pre><code>GET / HTTP/1.1 Host: User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/;q=0.8 Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3 Accept-Encoding: gzip, deflate DNT: 1 Connection: keep-alive, Upgrade Sec-WebSocket-Version: 13 Origin: Sec-WebSocket-Protocol: HyBi-00 Sec-WebSocket-Key: 65nHN33M6drIPjQHcGK8pA== Pragma: no-cache Cache-Control: no-cache Upgrade: websocket </code></pre> </div>


大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...


今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...


一 前言 此篇文章的内容也是学习不久,终于到周末有时间码一篇文章分享知识追寻者的粉丝们,学完本篇文章,读者将对token类的登陆认证流程有个全面的了解,可以动态搭建自己的登陆认证过程;对小项目而已是个轻量级的认证机制,符合开发需求;更多精彩原创内容关注公主号知识追寻者,读者的肯定,就是对作者的创作的最大支持; 二 jwt实现登陆认证流程 用户使用账号和面发出post请求 服务器接受到请求后使用私...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...



总结了 150 余个神奇网站,你不来瞅瞅吗?



提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...






私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...




今天给你们讲述一个外包程序员的幸福生活。男主是Z哥,不是在外包公司上班的那种,是一名自由职业者,接外包项目自己干。接下来讲的都是真人真事。 先给大家介绍一下男主,Z哥,老程序员,是我十多年前的老同事,技术大牛,当过CTO,也创过业。因为我俩都爱好喝酒、踢球,再加上住的距离不算远,所以一直也断断续续的联系着,我对Z哥的状况也有大概了解。 Z哥几年前创业失败,后来他开始干起了外包,利用自己的技术能...


场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...


阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...


不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...






当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...


HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...


硅谷科技公司上班时间OPEN早已不是什么新鲜事,早九晚五是常态,但有很多企业由于不打卡,员工们10点、11点才“姗姗来迟”的情况也屡见不鲜。 这种灵活的考勤制度为人羡慕,甚至近年来,国内某些互联网企业也纷纷效仿。不过,硅谷普遍弹性的上班制度是怎么由来的呢?这种“流行性迟到”真的有那么轻松、悠哉吗? 《动态规划专题班》 课程试听内容: 动态规划的解题要领 动态规划三大类 求最值/计数/可行性 常...






爬取彼岸桌面网站较为简单,用到了requests、lxml、Beautiful Soup4


编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?





已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...


前几天我们公司做了一件蠢事,非常非常愚蠢的事情。我原以为从学校出来之后,除了找工作有测试外,不会有任何与考试有关的事儿。 但是,天有不测风云,公司技术总监、人事总监两位大佬突然降临到我们事业线,叫上我老大,给我们组织了一场别开生面的“考试”。 那是一个风和日丽的下午,我翘着二郎腿,左手端着一杯卡布奇诺,右手抓着我的罗技鼠标,滚动着轮轴,穿梭在头条热点之间。 “淡黄的长裙~蓬松的头发...


在2019年的ReactiveConf 上,《Elm in Action》的作者Richard Feldman对未来5年Web开发的发展做了预测,很有意思,分享给大家。如果你有机会从头...