websocket写入关闭消息始终发送1006

我想向客户发送关闭代码,但始终为1006。</ p>

< p>我尝试过</ p>

  func ServeWs(w http.ResponseWriter,r * http.Request){
conn:= Upgrade(w,r)
msg:= websocket.FormatCloseMessage(4001,“ myError”)
//情况1
conn.WriteMessage(websocket.CloseMessage,msg)

//情况2
//conn.WriteControl(websocket.CloseMessage,msg, time.Now()。Add(time.Second))

//情况3
// w,err:= conn.NextWriter(websocket.CloseMessage)
//如果err!= nil {
// return
//}
//如果_,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)
返回nil
}
返回conn
}
</ code> </ pre>

但在所有这些情况下均无效。 如何将1006以外的数据发送给客户端?</ p>

我还测试了Node js ws软件包以验证客户端的身份。 </ p>

  const WebSocket = require('ws'); 

const ws = new WebSocket.Server({port:8088});

ws.on(' connection',函数connection(ws){
ws.close(1000,'bac');
});
</ code> </ pre>

此javascript代码工作正常。 </ p>

===已添加=== </ p>

用于测试的客户端代码。 在chrome开发工具控制台中,粘贴以下</ p>

  conn = new WebSocket(“ ws://127.0.0.1:8088 / connect”);  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>

展开原文

原文

I want to send close code to client, but It is always 1006.

I tried,

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
}

But Not worked all these cases. How can I send except 1006 to client?

I also tested Node js ws package to verify client's.

const WebSocket = require('ws');

const ws = new WebSocket.Server({ port: 8088 });

ws.on('connection', function connection(ws) {
  ws.close(1000, 'bac');
});

This javascript codes worked fine.

=== Added ===

Client Codes for testing. In chrome dev tool console, paste below

conn = new WebSocket("ws://127.0.0.1:8088/connect"); conn.onclose = function(evt){console.log("do", evt);}; conn.onerror = function(err){console.log("err", err);}; conn.onmessage = function(msg){console.log("msg", msg);};

doulang1945
doulang1945 我添加了我的升级功能。是因为没有头文件吗?我使用了来自此示例github.com/gorilla/websocket/blob/master/examples/chat/的代码
一年多之前 回复
douduandiao1368
douduandiao1368 请发布一个最小的可复制示例。特别是,显示升级代码
一年多之前 回复
dqrzot2791
dqrzot2791 大猩猩websocket代码对我有用,我在客户端中获得了预期的关闭代码。您调用Upgrade(w,r),但是(最新)大猩猩的正确签名是Upgrade(http.ResponseWriter,*http.Request,http.Header),例如拼写错误,或者您使用的是旧的大猩猩版本?
一年多之前 回复

1个回答



这都是因为“睡眠” </ p>

  // time.Sleep(  10 * time.Second)
conn.Close()
</ code> </ pre>

删除“睡眠”后,代码运行正常。</ p>
</ div>

展开原文

原文

This is all because the "Sleep"

//time.Sleep(10*time.Second)
conn.Close()

After removing Sleep, The code works fine.

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

<div class="post-text" itemprop="text"> <p>How is it possible to close a websocket connection and pass it a message / code?</p> <p>The docs only define <code>func (ws *Conn) Close() error</code> without any arguments</p> <p>I would like to receive the event from JavaScript like this:</p> <pre><code>websocket.onclose = function(event) { console.log(event); }; </code></pre> <p>I am using <a href="https://godoc.org/golang.org/x/net/websocket" rel="nofollow">golang.org/x/net/websocket</a></p> </div>

WebsocketServer:将事件消息发送到连接的客户端

<div class="post-text" itemprop="text"> <p>Problem is simple: i have WS server that doing it's "for {}". I need "register" connected user, then send message on event(outside of CoreWS function). I'm added NodeJS example that doing exactly what i need, for better understanding.</p> <p>Go Lang Code that fails: i'm using this pkg <a href="https://github.com/gobwas/ws" rel="nofollow noreferrer">https://github.com/gobwas/ws</a></p> <pre><code>var conn_itf interface{} //yeah, var op_itf interface{} //i know it's not how it works func main() { go collector() go sender() http.ListenAndServe(":3333", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { conn, _, _, err := ws.UpgradeHTTP(r, w) if err != nil { // handle error } go func() { defer conn.Close() for { msg, op, err := wsutil.ReadClientData(conn) conn_itf = conn // i'm trying to "register" user op_itf = op if err != nil { } err = wsutil.WriteServerMessage(conn, op, msg) if err != nil { } } }() })) } func collector() { for { fmt.Println("conn: ", conn_itf) fmt.Println("op: ", op_itf) time.Sleep(10000 * time.Millisecond) } } func sender() { for { msg := []byte("Hello world!") time.Sleep(50000 * time.Millisecond) wsutil.WriteServerMessage(conn_itf, op_itf, msg) //invoking ws-send } } </code></pre> <p>NodeJS that working:</p> <pre><code>const wss = new WebSocket.Server({ port: 3333 }) wss.on('connection', ws =&gt; { sockets.set('key', ws) //this code remember active connection ws.on('message', message =&gt; { console.log(`Received message =&gt; ${message}`) }) }) function callsend(data) { const ws = sockets.get('key') //this code sending message on invoking ws.send(data) } </code></pre> </div>

在客户端断开连接之前,Websocket不会发送消息

<div class="post-text" itemprop="text"> <p>I'm learning WebSocket using PHP library Ratchet. But I have a problem sending the message from client/browser. I have tried using chrome and firefox.</p> <p>The message is not sent to the server until I disconnect the client by closing the tab or refresh the browser.</p> <p>Update: My server use Centos 7 with firewalld enabled.</p> <p>After I close the browser tab, the server output is like this:</p> <pre><code>Connection 73 sending message "tes" to 1 other connection Connection 73 has disconnected </code></pre> <p>Here is the javascript code:</p> <pre><code>conn = new WebSocket('ws://websocket.develop.local:8080'); conn.onopen = function(e) { console.log("Connection established!"); }; conn.onmessage = function(e) { console.log('ada message'); console.log(e.data); }; conn.onerror = function(e) { console.log("WebSocket Error: " , e); //Custom function for handling errors //handleErrors(e); }; function sendMessage(){ var message = document.getElementById("pesan").value; conn.send(message); console.log('Sending message: ' + message); }; </code></pre> <p>And here is the PHP code (I got this from Ratchet docs):</p> <pre><code> &lt;?php namespace MyApp; use Ratchet\MessageComponentInterface; use Ratchet\ConnectionInterface; class Chat implements MessageComponentInterface { protected $clients; public function __construct() { $this-&gt;clients = new \SplObjectStorage; } public function onOpen(ConnectionInterface $conn) { // Store the new connection to send messages to later $this-&gt;clients-&gt;attach($conn); echo "New connection! ({$conn-&gt;resourceId}) "; } public function onMessage(ConnectionInterface $from, $msg) { $numRecv = count($this-&gt;clients) - 1; echo sprintf('Connection %d sending message "%s" to %d other connection%s' . " " , $from-&gt;resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's'); foreach ($this-&gt;clients as $client) { if ($from !== $client) { // The sender is not the receiver, send to each client connected $client-&gt;send($msg); } } } public function onClose(ConnectionInterface $conn) { // The connection is closed, remove it, as we can no longer send it messages $this-&gt;clients-&gt;detach($conn); echo "Connection {$conn-&gt;resourceId} has disconnected "; } public function onError(ConnectionInterface $conn, \Exception $e) { echo "An error has occurred: {$e-&gt;getMessage()} "; $conn-&gt;close(); } } </code></pre> </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>

如何知道spring websocket消息是否发送成功

spring boot: 1.3.3.RELEASE 现在服务端使用 SimpMessagingTemplate convertAndSendTouser() 推送消息给客户端,如何知道消息是否推送成功? 或者我想知道,如何获取所有用户的订阅信息?因为知道所有用户的订阅,就可以有针对的推送消息给指定用户。 假如客户端连上websocket后,客户端马上断网了,此时服务器往客户端推消息,为何没有报错?

WebSocket服务端发消息给客户端,浏览器收到消息就关闭了

自己按照 Websocket 的 文档写的, 浏览器每次连接上, 一收到消息就断开了 报错:WebSocket connection to 'ws://192.168.1.248:2051/' failed: A server must not mask any frames that it sends to the client. 但是 内容根本就没有mask 然后连网上别的websocket服务器,连上发消息正常, 然后直接对消息抓包 过来原文发送,还是包这个错误; wireshark 都能识别,但是 浏览器就是一收到就报错断开,,,快崩溃了了~~~~ 下面是发送的数据: char tt[250]={0x81,0x53,0x7b,0x22,0x6a,0x73,0x6f,0x6e,0x72,0x70 ,0x63,0x22,0x3a,0x22,0x32,0x2e,0x30,0x22,0x2c,0x22,0x65,0x72,0x72,0x6f,0x72,0x22 ,0x3a,0x7b,0x22,0x63,0x6f,0x64,0x65,0x22,0x3a,0x2d,0x31,0x30,0x30,0x30,0x30,0x32 ,0x2c,0x22,0x6d,0x65,0x73,0x73,0x61,0x67,0x65,0x22,0x3a,0x22,0x54,0x65,0x73,0x74 ,0x5f,0x56,0x61,0x6c,0x75,0x65,0x20,0x69,0x73,0x20,0x6e,0x6f,0x74,0x20,0x76,0x61 ,0x6c,0x69,0x64,0x20,0x6a,0x73,0x6f,0x6e,0x22,0x7d,0x7d,0};

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频繁发送大数据。

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

Golang Websocket客户端关闭了连接

<div class="post-text" itemprop="text"> <p>I have a golang connection. If the client opened the connection the database change the online column to 1. Here is my code but I didnt implement the last thing. My question, how can I change the database column to 0 if the client closed the connection. How can I track the client, and catch the connection close? </p> <pre><code>package main import ( "golang.org/x/net/websocket" "fmt" "log" "net/http" "strconv" ) type Clients struct { webs *websocket.Conn clientAddr string id int } var ( ActiveClients = make(map[Clients]int) ) func Echo(ws *websocket.Conn){ var err error client := ws.Request().RemoteAddr sockCli := Clients{webs: ws, clientAddr: client, id: 0} ActiveClients[sockCli] = 1 for{ var reply string if err = websocket.Message.Receive(ws, &amp;reply); err != nil{ fmt.Println("Cant receive", err) break }else{ if sockCli.id == 0{ sockCli.id, err = strconv.Atoi(reply) } } if err = websocket.Message.Send(ws, "id:"+strconv.Itoa(sockCli.id)); err != nil{ fmt.Println("Cant send") } for cs, _ := range ActiveClients { if cs.id == 1{ if err = websocket.Message.Send(cs.webs, "asd"); err != nil { // we could not send the message to a peer log.Println("Could not send message to ", cs.clientAddr, err.Error()) } }else { fmt.Println("No") } } } } func main(){ http.Handle("/", websocket.Handler(Echo)) if err := http.ListenAndServe(":1234", nil); err != nil{ log.Fatal("ListenAndServe: ", err) } } </code></pre> </div>

关于websocket,请问这两种发送消息方法有什么区别

1. webSocketSet.session.getBasicRemote().sendText(message); 2.session.getBasicRemote().sendText(message); 通过webSocketSet对象和不通过webSocketSet对象发送消息有什么不同吗?

业务sevice层如何调用 注解版WebSocket发送消息?

我现在的业务中需要用到websocket,实时向前端发送消息。现在我已经写好了注解板的websocket,但是在service层不知道怎么调用websocket的onMessage方法 向前台发送消息?求大神指点, 最好 写下伪代码。

如何从golang的websocket服务器向客户端主动发送消息

<div class="post-text" itemprop="text"> <p>I'm a newcomer for the golang and websocket.</p> <p>I'm trying to write a websocket server which can send the messages actively to client once the handshake is done.</p> <p>but my server will just only send the message to the client when got the request from the client.</p> <p>Does anyone know how to implement this feature or where can I find the related answer for that? </p> <p>Thank you so much.</p> <p>the source code is as follows:</p> <pre><code>package main import ( "log" "net/http" ) func handler(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "text/plain") w.Write([]byte("Hi, the handshake is completed. ")) w.Write([]byte("Let's start to talk something. ")) } func main() { http.HandleFunc("/", handler) log.Printf("Start to listen on 443.") err := http.ListenAndServeTLS(":443", "server.crt", "server.key", nil) log.Fatal(err) } </code></pre> </div>

将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服务端分段发送文件

websocket服务端如何分段发送文件给客户端,网上大部分都是客户端分段发送给服务端

websocket发送图片的二进制内容过长,该怎么办呢?

```javascript // 内容html 是前端 富文本编辑框summernote的内容 var html = $('.summernote').summernote('code'); if(html == null || html == ""){ layer.msg("聊天内容不能为空!!",{icon:5}); return false; } var msg = { msgContent: html, postsId: 1 }; // 发送消息到后台服务器 websocket.send(JSON.stringify(msg)); ``` 如果我的富文本编辑框里输入的是文字,则可以发送成功。 如果是选中的图片,则内容html是图片的二进制,并且还比较长,websocket自动关闭了,提示错误是:**发送内容太长**? 有大神做过没有呢,请指教!!!!! 其他的都还好,就是内容太长,websocket连接会被强制关闭。

websocket 推送消息通知

就比如我要发帖 点发帖会提示我有一个未结的帖子消息通知,使用websocket怎么做的哦? websocket服务端怎么查询数据库?项目用的struts

从websocket收到消息时,不会导致“ Websocket:关闭1011”

<div class="post-text" itemprop="text"> <p>I'm trying to subscribe to an event from a client to a server. I can subscribe to the event using JavaScript but when I use <code>Golang</code> and the <code>Gorilla Websocket library</code> I get a</p> <blockquote> <p>'websocket: close 1011 (internal server error)'</p> </blockquote> <p>every time I start a read from the socket.</p> <p>I tried using the <code>/x/websocket</code> library as well but when I tried to read from the socket I end up hanging and I dont get the '1011' error.</p> <p>If I use this JavaScript code on my browser it works:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;script&gt; var socket = new WebSocket("ws://blehip:blehpport"); function send(data) { socket.send(JSON.stringify(data)); } socket.onopen = function() { send({ action: 'subscribe', auth_token: 'Bleh', request_id: 'Bleh', data: { account_id: 'bleh', binding: "bleh" } }); } socket.onmessage = function(raw_message) { var json_data = JSON.parse(raw_message.data); console.log(json_data); }; &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I get a stream of JSON objects in real time.</p> <p>This is my small Golang, Gorilla/Websockets script</p> <pre><code>func main() { var server = flag.String("server", "blehIP:BlehPort", "server address") var wg sync.WaitGroup flag.Parse() url := url.URL { Scheme: "ws", Host: *server, Path: "", } conn, _, err := websocket.DefaultDialer.Dial(url.String(), nil) if err != nil { log.Fatal("Dial Error: ", err) } defer conn.Close() payload := []byte(`{"action":"subscribe",`+ `"auth_token":"` + bleh + `",`+ `"request_id":"` + bleh + `",`+ `"data": {`+ `"account_id":"` + bleh + `",`+ `"binding":"` + bleh + `"}`+ `}`) wg.Add(1) go func() { defer conn.Close() defer wg.Done() err = conn.WriteMessage(websocket.TextMessage, payload) if err != nil { log.Println("Write Error: ", err) return } m := frame{} err := conn.ReadJSON(&amp;m) if err != nil { log.Println("WebScoket closed.", err) return } // msg := string(bytes[:]) fmt.Printf("%v", m) }() wg.Wait() return } </code></pre> <blockquote> <p>The error returned is: WebSocket closed. websocket: close 1011 (internal server error)</p> </blockquote> </div>

Golang Websocket自定义JSON消息

<div class="post-text" itemprop="text"> <p>I'm trying to send/receive custom JSON messages. There are 3 cases in which the JSON struct changes, therefore I have 3 different structs. I have to access the room string which is sent as RawMessage. My question is what type should the channel Broadcast be?</p> <pre><code>type Message struct { Type int64 `json:"type"` Msg json.RawMessage } </code></pre> <p><code>Broadcast chan interface{} // ??? RawMessage or maybe interface</code></p> <pre><code> case m := &lt;-r.Broadcast: // What type should chan Broadcast be? // If m is of type json.RawMessage should I deal with unmarshalling here? connections := r.Clients[m.Room] // for c := range connections { select { case c.send &lt;- m: default: close(c.send) delete(connections, c) if len(connections) == 0 { delete(r.Clients, m.Room) } } } </code></pre> <pre><code>for { msg := &amp;Message{} err := c.conn.ReadJSON(&amp;msg) // _, msg, err := c.conn.ReadMessage() if err != nil { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) { log.Printf("error: %v", err) } break } if msg.Type == 0 { newVideo := &amp;NewVideo{} if err = json.Unmarshal(msg.Msg, &amp;newVideo); err != nil { fmt.Println(err) } Roomb.Broadcast &lt;- msg.Msg // ??? should i send the RawMessage online[msg.Room] = msg } else if msg.Type == 1 { if _, ok := online[msg.Room]; ok { online[msg.Room].Start = float64(time.Now().Unix() - online[msg.Room].Timestamp) c.send &lt;- online[msg.Room] } } else if msg.Type == 2 { Roomb.Broadcast &lt;- msg.Msg // ??? should i send the RawMessage } fmt.Println(msg) } </code></pre> </div>

docker容器上的Golang Websocket服务器不会向外界发送消息

<div class="post-text" itemprop="text"> <p>I have a golang backend, node frontend. And it worked both on windows and ubuntu without docker. Now I am trying to dockerize everything. I put both backend and frontend in the same docker container. I can establish initial connection but later the backend kept throwing error like this: <a href="https://i.stack.imgur.com/5gl4H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5gl4H.png" alt="Error message printed by golang"></a></p> <p>I have exposed port 8000 to 8004, the ws port is 8000 and frontend port is 8004. I have tried both --net=host as well as exposing everything as host ip address 192.168.1.4. Non of them worked.</p> <p>On the browser side, the websocket client always get 101 response like this: <a href="https://i.stack.imgur.com/I1boX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I1boX.png" alt="Screenshot from chrome"></a></p> <p>I think it could be a config problem on docker. But I have no lead right now on how to deal with this. The browser tested is Chrome 55 on windows 10. Docker, golang and node are of the latest. The host machine is on Ubuntu 16.10 as well as container os.</p> </div>

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

董付国系列教材《Python程序设计基础》、《Python程序设计(第2版)》、《Python可以这样学》配套视频,讲解Python 3.5.x和3.6.x语法、内置对象用法、选择与循环以及函数设计与使用、lambda表达式用法、字符串与正则表达式应用、面向对象编程、文本文件与二进制文件操作、目录操作与系统运维、异常处理结构。

获取Linux下Ftp目录树并逐步绑定到treeview

在linux下抓取目录树,双击后获取该节点子节点(逐步生成)。另外有两个类,一个是windows下的(一次性获取目录树),一个是linux下的(足部获取目录树)

NS网络模拟和协议仿真源代码

NS网络模拟和协议仿真源代码,包含代码说明及协议分析

简单的NS3网络模拟仿真(计算机网络作业)

简单的NS3网络模拟仿真,内附有PPT演示。论文评述。以及简单的安装教程。

手把手实现Java图书管理系统(附源码)

【超实用课程内容】 本课程演示的是一套基于Java的SSM框架实现的图书管理系统,主要针对计算机相关专业的正在做毕设的学生与需要项目实战练习的java人群。详细介绍了图书管理系统的实现,包括:环境搭建、系统业务、技术实现、项目运行、功能演示、系统扩展等,以通俗易懂的方式,手把手的带你从零开始运行本套图书管理系统,该项目附带全部源码可作为毕设使用。 【课程如何观看?】 PC端:https://edu.csdn.net/course/detail/27513 移动端:CSDN 学院APP(注意不是CSDN APP哦) 本课程为录播课,课程2年有效观看时长,大家可以抓紧时间学习后一起讨论哦~ 【学员专享增值服务】 源码开放 课件、课程案例代码完全开放给你,你可以根据所学知识,自行修改、优化

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

从事大数据与人工智能开发与实践约十年,钱老师亲自见证了大数据行业的发展与人工智能的从冷到热。事实证明,计算机技术的发展,算力突破,海量数据,机器人技术等,开启了第四次工业革命的序章。深度学习图像分类一直是人工智能的经典任务,是智慧零售、安防、无人驾驶等机器视觉应用领域的核心技术之一,掌握图像分类技术是机器视觉学习的重中之重。针对现有线上学习的特点与实际需求,我们开发了人工智能案例实战系列课程。打造:以项目案例实践为驱动的课程学习方式,覆盖了智能零售,智慧交通等常见领域,通过基础学习、项目案例实践、社群答疑,三维立体的方式,打造最好的学习效果。

150讲轻松搞定Python网络爬虫

【为什么学爬虫?】 &nbsp; &nbsp; &nbsp; &nbsp;1、爬虫入手容易,但是深入较难,如何写出高效率的爬虫,如何写出灵活性高可扩展的爬虫都是一项技术活。另外在爬虫过程中,经常容易遇到被反爬虫,比如字体反爬、IP识别、验证码等,如何层层攻克难点拿到想要的数据,这门课程,你都能学到! &nbsp; &nbsp; &nbsp; &nbsp;2、如果是作为一个其他行业的开发者,比如app开发,web开发,学习爬虫能让你加强对技术的认知,能够开发出更加安全的软件和网站 【课程设计】 一个完整的爬虫程序,无论大小,总体来说可以分成三个步骤,分别是: 网络请求:模拟浏览器的行为从网上抓取数据。 数据解析:将请求下来的数据进行过滤,提取我们想要的数据。 数据存储:将提取到的数据存储到硬盘或者内存中。比如用mysql数据库或者redis等。 那么本课程也是按照这几个步骤循序渐进的进行讲解,带领学生完整的掌握每个步骤的技术。另外,因为爬虫的多样性,在爬取的过程中可能会发生被反爬、效率低下等。因此我们又增加了两个章节用来提高爬虫程序的灵活性,分别是: 爬虫进阶:包括IP代理,多线程爬虫,图形验证码识别、JS加密解密、动态网页爬虫、字体反爬识别等。 Scrapy和分布式爬虫:Scrapy框架、Scrapy-redis组件、分布式爬虫等。 通过爬虫进阶的知识点我们能应付大量的反爬网站,而Scrapy框架作为一个专业的爬虫框架,使用他可以快速提高我们编写爬虫程序的效率和速度。另外如果一台机器不能满足你的需求,我们可以用分布式爬虫让多台机器帮助你快速爬取数据。 &nbsp; 从基础爬虫到商业化应用爬虫,本套课程满足您的所有需求! 【课程服务】 专属付费社群+每周三讨论会+1v1答疑

cuda开发cutilDLL

包括cutil32.dll、cutil32D.dll、cutil32.lib、cutil32D.lib,以及附带的glew32.lib/freeglut.lib

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

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

Tensorflow与python3.7适配版本

tensorflow与python3.7匹配的最新库,更新了python3.7以后可以自行下载,或者去国外python的扩展包下载界面自行下载。

4小时玩转微信小程序——基础入门与微信支付实战

这是一个门针对零基础学员学习微信小程序开发的视频教学课程。课程采用腾讯官方文档作为教程的唯一技术资料来源。杜绝网络上质量良莠不齐的资料给学员学习带来的障碍。 视频课程按照开发工具的下载、安装、使用、程序结构、视图层、逻辑层、微信小程序等几个部分组织课程,详细讲解整个小程序的开发过程

专为程序员设计的数学课

<p> 限时福利限时福利,<span>15000+程序员的选择!</span> </p> <p> 购课后添加学习助手(微信号:csdn590),按提示消息领取编程大礼包!并获取讲师答疑服务! </p> <p> <br> </p> <p> 套餐中一共包含5门程序员必学的数学课程(共47讲) </p> <p> 课程1:《零基础入门微积分》 </p> <p> 课程2:《数理统计与概率论》 </p> <p> 课程3:《代码学习线性代数》 </p> <p> 课程4:《数据处理的最优化》 </p> <p> 课程5:《马尔可夫随机过程》 </p> <p> <br> </p> <p> 哪些人适合学习这门课程? </p> <p> 1)大学生,平时只学习了数学理论,并未接触如何应用数学解决编程问题; </p> <p> 2)对算法、数据结构掌握程度薄弱的人,数学可以让你更好的理解算法、数据结构原理及应用; </p> <p> 3)看不懂大牛代码设计思想的人,因为所有的程序设计底层逻辑都是数学; </p> <p> 4)想学习新技术,如:人工智能、机器学习、深度学习等,这门课程是你的必修课程; </p> <p> 5)想修炼更好的编程内功,在遇到问题时可以灵活的应用数学思维解决问题。 </p> <p> <br> </p> <p> 在这门「专为程序员设计的数学课」系列课中,我们保证你能收获到这些:<br> <br> <span> </span> </p> <p class="ql-long-24357476"> <span class="ql-author-24357476">①价值300元编程课程大礼包</span> </p> <p class="ql-long-24357476"> <span class="ql-author-24357476">②应用数学优化代码的实操方法</span> </p> <p class="ql-long-24357476"> <span class="ql-author-24357476">③数学理论在编程实战中的应用</span> </p> <p class="ql-long-24357476"> <span class="ql-author-24357476">④程序员必学的5大数学知识</span> </p> <p class="ql-long-24357476"> <span class="ql-author-24357476">⑤人工智能领域必修数学课</span> </p> <p> <br> 备注:此课程只讲程序员所需要的数学,即使你数学基础薄弱,也能听懂,只需要初中的数学知识就足矣。<br> <br> 如何听课? </p> <p> 1、登录CSDN学院 APP 在我的课程中进行学习; </p> <p> 2、登录CSDN学院官网。 </p> <p> <br> </p> <p> 购课后如何领取免费赠送的编程大礼包和加入答疑群? </p> <p> 购课后,添加助教微信:<span> csdn590</span>,按提示领取编程大礼包,或观看付费视频的第一节内容扫码进群答疑交流! </p> <p> <img src="https://img-bss.csdn.net/201912251155398753.jpg" alt=""> </p>

实现简单的文件系统

实验内容: 通过对具体的文件存储空间的管理、文件的物理结构、目录结构和文件操作的实现,加深对文件系统内部功能和实现过程的理解。 要求: 1.在内存中开辟一个虚拟磁盘空间作为文件存储器,在其上实现一个简

机器学习初学者必会的案例精讲

通过六个实际的编码项目,带领同学入门人工智能。这些项目涉及机器学习(回归,分类,聚类),深度学习(神经网络),底层数学算法,Weka数据挖掘,利用Git开源项目实战等。

四分之一悬架模型simulink.7z

首先建立了四分之一车辆悬架系统的数学模型,应用MATLAB/Simulink软件建立该系统的仿真模型,并输入路面激励为随机激励,控制不同的悬架刚度和阻尼,选用最优的参数得到车辆悬架的振动加速度变化曲线

MFC一站式终极全套课程包

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

C++语言基础视频教程

C++语言基础视频培训课程:本课与主讲者在大学开出的程序设计课程直接对接,准确把握知识点,注重教学视频与实践体系的结合,帮助初学者有效学习。本教程详细介绍C++语言中的封装、数据隐藏、继承、多态的实现等入门知识;主要包括类的声明、对象定义、构造函数和析构函数、运算符重载、继承和派生、多态性实现等。 课程需要有C语言程序设计的基础(可以利用本人开出的《C语言与程序设计》系列课学习)。学习者能够通过实践的方式,学会利用C++语言解决问题,具备进一步学习利用C++开发应用程序的基础。

Java8零基础入门视频教程

这门课程基于主流的java8平台,由浅入深的详细讲解了java SE的开发技术,可以使java方向的入门学员,快速扎实的掌握java开发技术!

HoloLens2开发入门教程

本课程为HoloLens2开发入门教程,讲解部署开发环境,安装VS2019,Unity版本,Windows SDK,创建Unity项目,讲解如何使用MRTK,编辑器模拟手势交互,打包VS工程并编译部署应用到HoloLens上等。

C/C++学习指南全套教程

C/C++学习的全套教程,从基本语法,基本原理,到界面开发、网络开发、Linux开发、安全算法,应用尽用。由毕业于清华大学的业内人士执课,为C/C++编程爱好者的教程。

pokemmo的资源

pokemmo必须的4个rom 分别为绿宝石 火红 心金 黑白 还有汉化补丁 资源不错哦 记得下载

test_head.py

本文件主要是针对使用dlib的imglab标注工具标记的目标检测框和关键点检测而生成的xml文件, 转换为coco数据集格式.

Java面试史上最全的JAVA专业术语面试100问 (前1-50)

前言: 说在前面, 面试题是根据一些朋友去面试提供的,再就是从网上整理了一些。 先更新50道,下一波吧后面的也更出来。 求赞求关注!! 废话也不多说,现在就来看看有哪些面试题 1、面向对象的特点有哪些? 抽象、继承、封装、多态。 2、接口和抽象类有什么联系和区别? 3、重载和重写有什么区别? 4、java有哪些基本数据类型? 5、数组有没有length()方法?String有没有length()方法? 数组没有length()方法,它有length属性。 String有length()方法。 集合求长度用

2019 AI开发者大会

2019 AI开发者大会(AI ProCon 2019)是由中国IT社区CSDN主办的AI技术与产业年度盛会。多年经验淬炼,如今蓄势待发:2019年9月6-7日,大会将有近百位中美顶尖AI专家、知名企业代表以及千余名AI开发者齐聚北京,进行技术解读和产业论证。我们不空谈口号,只谈技术,诚挚邀请AI业内人士一起共铸人工智能新篇章!

linux“开发工具三剑客”速成攻略

工欲善其事,必先利其器。Vim+Git+Makefile是Linux环境下嵌入式开发常用的工具。本专题主要面向初次接触Linux的新手,熟练掌握工作中常用的工具,在以后的学习和工作中提高效率。

DirectX修复工具V4.0增强版

DirectX修复工具(DirectX Repair)是一款系统级工具软件,简便易用。本程序为绿色版,无需安装,可直接运行。 本程序的主要功能是检测当前系统的DirectX状态,如果发现异常则进行修复

20行代码教你用python给证件照换底色

20行代码教你用python给证件照换底色

2019 Python开发者日-培训

本次活动将秉承“只讲技术,拒绝空谈”的理念,邀请十余位身处一线的Python技术专家,重点围绕Web开发、自动化运维、数据分析、人工智能等技术模块,分享真实生产环境中使用Python应对IT挑战的真知灼见。此外,针对不同层次的开发者,大会还安排了深度培训实操环节,为开发者们带来更多深度实战的机会。

我以为我对Mysql事务很熟,直到我遇到了阿里面试官

太惨了,面试又被吊打

相关热词 c#分级显示数据 c# 不区分大小写替换 c#中调用就java c#正则表达式 验证小数 c# vscode 配置 c#三维数组能存多少数据 c# 新建excel c#多个文本框 c#怎么创建tcp通讯 c# mvc 电子病例
立即提问