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

在做活体检测的项目,前端一直采集头像发送给后端处理,
采用websocket协议,前端以1M/s的速度发送图片的base64码给后端这种方式,
websocket建立连接开始发送数据,大概几秒后,websocket就会断开连接,
如果此时再刷新页面尝试重新建立连接,tomcat有时会宕机。

4个回答

看看Tomcat日志,是不是处理不过来,网络连接被终止了。服务器有没有流量限制

你的base64字符串怎么生成的,是stringbuffer么?是否溢出了。另外有没有并发造成的死锁,这个要调试下看看。

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

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

要么缩小客户端发送的数据量
要么放大服务端接收的缓冲区

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
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>

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>

如何使用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>

python3实现websocket协议发送二进制数据给客户端的问题。

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

此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>

Gorilla Websocket手动关闭客户端连接

<div class="post-text" itemprop="text"> <p>I try to close connect manual(use <a href="https://dwst.github.io/" rel="nofollow noreferrer">Dark WebSocket Terminal</a>),but the client tell me 1005 (No Status Rcvd)<br> Server:</p> <pre><code>ReadLoop: for { mt, message, err := c.ReadMessage() if err != nil { log.Println("read:", err) log.Println("messageType:", mt) if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) { log.Printf("error: %v", err) } c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) break ReadLoop } log.Printf("recv: %s", message) //do sth in here err = c.WriteMessage(mt, message) if err != nil { //WriteMessage wrong log.Println("write:", err) break ReadLoop } } </code></pre> <p>It is not work and show the expected outputting the following:</p> <pre><code>read: websocket: close 1005 (no status) messageType: -1 error: websocket: close 1005 (no status) </code></pre> <p>How should i go about this?</p> </div>

python后端接收到数据,怎么主动发送给前端呢?

现在想通过udp做一个聊天小案列,数据展示都是在前端,问题是,后端接受到消息后不知道怎么主动向前端提交。

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>

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--; } } ```

websocket-一Ping/Pong就出错

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

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\" } }");

怎么调用websocket作为通道发送数据

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

使用错误的WebSocket协议在gorilla / websocket / client.go的Dial函数中返回“意外的EOF”错误

<div class="post-text" itemprop="text"> <p>I was trying to connect to a server in Go by using <a href="https://github.com/gorilla/websocket" rel="nofollow noreferrer">gorilla/websocket</a> and I kept getting the error "unexpected EOF". It took me way too long to find out it was because I needed to use the secure WebSocket protocol to connect to that server ("wss://" instead of "ws://" in my url).</p> <p>How can I verify that I'm using the wrong protocol for a given endpoint so that I can log a helpful error message instead of "unexpected EOF"?</p> </div>

后端实时获取类似json格式的数据,获取后进行处理,传向前端页面,前端可以实时显示处理后的数据?

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

将Websocket消息发送到Go中的特定客户端(使用Gorilla)

<div class="post-text" itemprop="text"> <p>I am very new to Go and have found myself working with sockets as my first project. This is a redundant question, but I have failed to understand how to send a websocket update to a specific client in Go (using Gorilla).</p> <p>The broad problem that I am trying to solve is - Building a typeahead using websockets and a search engine like ES/Lucene. I have maintained a bunch of indexes on my search engine and have a Go wrapper around it. When I started working on using websockets in Go, I have been finding almost all the examples showing broadcasting mechanism. When I tried to dig into this and tried to modify the example given in Gorilla's github <a href="https://github.com/gorilla/websocket/tree/master/examples/chat" rel="nofollow noreferrer">repo</a> based on the examples given in <a href="https://github.com/gorilla/websocket/issues/46" rel="nofollow noreferrer">this</a> thread and in this <a href="https://stackoverflow.com/questions/31598147/how-to-send-to-only-one-client-and-not-all-clients-using-go-and-gorilla-websocke">answer</a>, I don't seem to understand <code>connections</code> and how does that fit in <code>client.go</code></p> <p>Ideally, the way I would like to see this working is -</p> <ul> <li>A socket connection between the client and server is established</li> <li>Upon the client sending inputs via the socket, the server fetches it and throws into into a channel (Go channel)</li> <li>The indexing wrapper checks for this channel, and once there is something to fetch, the index is retrieved and written back to the socket</li> </ul> <p>How can the server uniquely identify the <code>Client</code>?</p> <p>I have used the examples given on Gorilla's Github <a href="https://github.com/gorilla/websocket/tree/master/examples/chat" rel="nofollow noreferrer">repo</a></p> <p>From my codebase <code>hub.go</code> has the following </p> <pre><code>type Hub struct { // Registered clients. clients map[*Client]bool // Inbound messages from the clients. broadcast chan []byte // Register requests from the clients. register chan *Client // Unregister requests from clients. unregister chan *Client connections map[string]*connection } func newHub() *Hub { return &amp;Hub{ broadcast: make(chan []byte), register: make(chan *Client), unregister: make(chan *Client), clients: make(map[*Client]bool), connection: make(map[*Client]bool), // is this alright? } } func (h *Hub) run() { for { select { case client := &lt;-h.register: h.clients[client] = true case client := &lt;-h.unregister: if _, ok := h.clients[client]; ok { delete(h.clients, client) close(client.send) } case message := &lt;-h.broadcast: for client := range h.connections { select { case client.send &lt;- message: default: close(client.send) delete(h.connections, client) } } } } } </code></pre> <p>and I am unsure with what I should be adding to <code>client.go</code></p> <pre><code>type Client struct { // unique ID for each client // id string // Hub object hub *Hub // The websocket connection. conn *websocket.Conn // Buffered channel of outbound messages. send chan []byte // connection --&gt; (what should the connection property be?) connection string } </code></pre> <p>Please note - I will be adding an <code>Id</code> field within the <code>Client</code> struct. How can I proceed from here?</p> </div>

websocket频繁发送大数据。

springboot项目,使用websocket持续给前端(vue)发送数据。但是会经常中断,不发数据了,记录在线人数的功能正常,如果有新的登录或者登出,后台正常显示。就是不发数据了,需要重启项目才会发数据。 ``` package com.smart.common.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.concurrent.CopyOnWriteArraySet; /** * @Description: websocket工具类, * flag表示身份标识: * bigScreen:大屏 * backSys:后台系统 */ @ServerEndpoint("/websocket/{flag}") @Component public class WebSocketUtils { private Logger logger = LoggerFactory.getLogger(getClass()); public static final String BIGSCREEN = "bigScreen"; //大屏 public static final String BACKSYS = "backSys"; //后台 //静态变量,用来记录当前在线连接数 private static int onlineCount = 0; //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。 private static CopyOnWriteArraySet<WebSocketUtils> webSocketSet = new CopyOnWriteArraySet<>(); //与某个客户端的连接会话,需要通过它来给客户端发送数据 private Session session; /** * 身份标识 */ private String flag; /** * 连接建立成功调用的方法 * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据 */ @OnOpen public void onOpen(@PathParam("flag") String flag, Session session){ this.session = session; this.flag = flag; webSocketSet.add(this); addOnlineCount(); //在线数加1 logger.info("有新连接加入!当前在线人数为" + getOnlineCount()+",上线用户为:"+this.flag); } /** * 连接关闭调用的方法 */ @OnClose public void onClose(){ webSocketSet.remove(this); subOnlineCount(); //在线数减1 logger.info("有一连接关闭!当前在线人数为" + getOnlineCount()+",下线用户为:"+this.flag); } /** * 收到客户端消息后调用的方法 * @param message 客户端发送过来的消息 * @param session 可选的参数 */ @OnMessage public void onMessage(String message, Session session) { //解析message if(message==null){ session.getAsyncRemote().sendText("发送的消息不能为空"); }else{ } } /** * 发生错误时调用 * @param session * @param error */ @OnError public void onError(Session session, Throwable error){ logger.info("发生错误:"+error.getMessage()); error.printStackTrace(); } /** * 群发消息 * @param message * @throws IOException */ public void sendMessageToFlag(String message){ for (WebSocketUtils ws : webSocketSet){ try{ ws.sendMessage(message); }catch (Exception e){ logger.error("sendMessageToFlag: "+e.toString()); } } } /** * 给指定身份发送消息 * @param message * @param flag * @throws IOException */ public void sendMessageToFlag(String message,String flag){ try{ boolean online = true; for (WebSocketUtils ws : webSocketSet){ if (flag.equals(ws.flag)){ ws.sendMessage(message); online = false; } } if (online){ logger.info(flag+"不在线"); } }catch (Exception e){ logger.error("sendMessageToFlag: "+e.toString()); } } public boolean isonline(){ boolean online = false; for (WebSocketUtils ws : webSocketSet){ if (BIGSCREEN.equals(ws.flag)){ online = true; } } return online; } public void sendMessageToBigScreen(String message){ sendMessageToFlag(message,BIGSCREEN); } public void snedMessage2BackSys(String message){ sendMessageToFlag(message,BACKSYS); } /** * 服务器主动推送消息到客户端 * @param message * @throws IOException */ private void sendMessage(String message) throws IOException { synchronized(this.session){ this.session.getBasicRemote().sendText(message); } System.out.println("发送数据给:"+this.flag+":"+message); } private static synchronized int getOnlineCount() { return onlineCount; } private static synchronized void addOnlineCount() { WebSocketUtils.onlineCount++; } private static synchronized void subOnlineCount() { WebSocketUtils.onlineCount--; } } ```

与“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://127.0.0.1:5555'); // Binding to 127.0.0.1 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('0.0.0.0:8080', $loop); // Binding to 0.0.0.0 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>http://192.168.12.52:8094/xyz/new/.... </code></pre> <p>我还尝试在客户端脚本中指定IP:</p> <pre><code>var conn = new ab.Session('ws://192.168.12.52:8080', function() { /* subscribe to following topics */ conn.subscribe('new_order', function(topic, data) ... </code></pre> <p>在这种情况下,我会得到以下错误:</p> <pre><code>WebSocket connection to 'ws://192.168.11.32:8080/' failed: Error during WebSocket handshake: Unexpected response code: 403 </code></pre> <p>这里缺少什么?</p> </div>

Golang WebSocket数据不正确

<div class="post-text" itemprop="text"> <p>I'm using <code>x.net.websocket</code> to read data from a websocket. The data is relatively large. When I read it, I can't read it completely, so it is cut off. Is there any way to solve it? </p> <pre><code>func receiveWebsocket(ws *websocket.Conn) error { for { var msg = make([]byte, 1024*1024) // 1024kb m, err := ws.Read(msg) if err != nil { log15.Error("ws read error", "error", err) return err } fmt.Println("length ---",m, string(msg)) response := string(msg[:m]) assignmentWebsocket(response) } } </code></pre> <p>According to the log, the <code>m</code> value is always 4092, even if <code>msg</code> is very large.</p> </div>

YOLOv3目标检测实战:训练自己的数据集

YOLOv3目标检测实战:训练自己的数据集

150讲轻松搞定Python网络爬虫

150讲轻松搞定Python网络爬虫

实用主义学Python(小白也容易上手的Python实用案例)

实用主义学Python(小白也容易上手的Python实用案例)

我说我不会算法,阿里把我挂了。

不说了,字节跳动也反手把我挂了。

立方体线框模型透视投影 (计算机图形学实验)

计算机图形学实验 立方体线框模型透视投影 的可执行文件,亲测可运行,若需报告可以联系我,期待和各位交流

2019 AI开发者大会

2019 AI开发者大会

组成原理课程设计(实现机器数的真值还原等功能)

实现机器数的真值还原(定点小数)、定点小数的单符号位补码加减运算、定点小数的补码乘法运算和浮点数的加减运算。

C/C++跨平台研发从基础到高阶实战系列套餐

一 专题从基础的C语言核心到c++ 和stl完成基础强化; 二 再到数据结构,设计模式完成专业计算机技能强化; 三 通过跨平台网络编程,linux编程,qt界面编程,mfc编程,windows编程,c++与lua联合编程来完成应用强化 四 最后通过基于ffmpeg的音视频播放器,直播推流,屏幕录像,

MFC一站式终极全套课程包

该套餐共包含从C小白到C++到MFC的全部课程,整套学下来绝对成为一名C++大牛!!!

软件测试2小时入门

软件测试2小时入门

三个项目玩转深度学习(附1G源码)

三个项目玩转深度学习(附1G源码)

计算机图形学-球的光照模型课程设计

计算机图形学-球的光照模型,有代码完美运行,有课程设计书

Linux常用命令大全(非常全!!!)

Linux常用命令大全(非常全!!!) 最近都在和Linux打交道,感觉还不错。我觉得Linux相比windows比较麻烦的就是很多东西都要用命令来控制,当然,这也是很多人喜欢linux的原因,比较短小但却功能强大。我将我了解到的命令列举一下,仅供大家参考: 系统信息 arch 显示机器的处理器架构 uname -m 显示机器的处理器架构 uname -r 显示正在使用的内核版本 d...

因为看了这些书,我大二就拿了华为Offer

四年了,四年,你知道大学这四年我怎么过的么?

深度学习原理+项目实战+算法详解+主流框架(套餐)

深度学习系列课程从深度学习基础知识点开始讲解一步步进入神经网络的世界再到卷积和递归神经网络,详解各大经典网络架构。实战部分选择当下最火爆深度学习框架PyTorch与Tensorflow/Keras,全程实战演示框架核心使用与建模方法。项目实战部分选择计算机视觉与自然语言处理领域经典项目,从零开始详解算法原理,debug模式逐行代码解读。适合准备就业和转行的同学们加入学习! 建议按照下列课程顺序来进行学习 (1)掌握深度学习必备经典网络架构 (2)深度框架实战方法 (3)计算机视觉与自然语言处理项目实战。(按照课程排列顺序即可)

fakeLocation13.5.1.zip

fakeLocation13.5.1 虚拟定位 ios13.5.1的最新驱动下载,iPhone/iPad免越狱虚拟定位工具Location-cleaned驱动已更新

UnityLicence

UnityLicence

Python可以这样学(第一季:Python内功修炼)

Python可以这样学(第一季:Python内功修炼)

Python+OpenCV计算机视觉

Python+OpenCV计算机视觉

土豆浏览器

土豆浏览器可以用来看各种搞笑、电影、电视剧视频

【数据结构与算法综合实验】欢乐连连看(C++ & MFC)案例

这是武汉理工大学计算机学院数据结构与算法综合实验课程的第三次项目:欢乐连连看(C++ & MFC)迭代开发代码。运行环境:VS2017。已经实现功能:开始游戏、消子、判断胜负、提示、重排、计时、帮助。

php+mysql学生成绩管理系统

学生成绩管理系统,分三个模块:学生,教师和管理员。 管理员模块:负责学生、老师信息的增删改;发布课程信息的增删改,以便让学生选课;审核老师提交的学生成绩并且打印成绩存档;按照课号查询每个课号的学生成绩

多功能数字钟.zip

利用数字电子计数知识设计并制作的数字电子钟(含multisim仿真),该数字钟具有显示星期、24小时制时间、闹铃、整点报时、时间校准功能

推荐24个国外黄色网站欣赏

在中国清朝,明黄色的衣服只有皇子才有资格穿,慢慢的黄色在中国就成了高贵的颜色。在人们的色彩印象中,黄色也表现为暂停。所以当你的网页设计采用黄色的时候,会让人们在你的网页前停留。 黄色,就像橙色和红色,黄色也是一个暖色。它有大自然、阳光、春天的涵义,而且通常被认为是一个快乐和有希望的色彩。黄色是所有色相中最能发光的颜色,给人轻快,透明,辉煌,充满希望的色彩印象。 黄色是一个高可见的色...

u-boot-2015.07.tar.bz2

uboot-2015-07最新代码,喜欢的朋友请拿去

一学即懂的计算机视觉(第一季)

一学即懂的计算机视觉(第一季)

学生成绩管理系统(PHP + MYSQL)

做的是数据库课程设计,使用的php + MySQL,本来是黄金搭配也就没啥说的,推荐使用wamp服务器,里面有详细的使用说明,带有界面的啊!呵呵 不行的话,可以给我留言!

Windows版YOLOv4目标检测实战:训练自己的数据集

Windows版YOLOv4目标检测实战:训练自己的数据集

C++语言基础视频教程

C++语言基础视频教程

玩转Python-Python3基础入门

玩转Python-Python3基础入门

相关热词 c# cad插入影像 c#设计思想 c#正则表达式 转换 c#form复制 c#写web c# 柱形图 c# wcf 服务库 c#应用程序管理器 c#数组如何赋值给数组 c#序列化应用目的博客园
立即提问