有关python websocket client的问题 10C

js版本上可以收到数据,用的是网上的websocket测试器,发送一个字典指令就可以源源不断收到json格式数据,如图所示:
图片说明
我用python搭建websocket client后控制端却没有回显,如图:
图片说明
请问各位大牛,错误之处在哪,如何用python获取源源不断的json格式数据。

1个回答

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
python3+websocket解析遇到中文乱码

握手成功后前端向服务器发送报文信息,信息内容有中文。解析过程中如何解决乱码问题? msg = decode1(self.conn.recv(1024)) #接收报文 #解析报文 def decode(data): if not len(data): return False length = data[1] & 127 if length == 126: mask = data[4:8] raw = data[8:] elif length == 127: mask = data[10:14] raw = data[14:] else: mask = data[2:6] raw = data[6:] ret = '' for cnt, d in enumerate(raw): ret += chr(d ^ mask[cnt % 4]) return ret

websocket client执行socket_write 就断开连接

php 充当websocket客户端,模拟向服务器端发消息,但是一执行socket_write连接就丢失了。 是因为php是短连接吗?我在服务端有监控发送的消息,没有收到消息。 代码: $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); $result = socket_connect($socket, '********', ***); echo $result."\n"; echo "Send Command..........\n"; $msg = 'test msg'; socket_write($socket, $msg, strlen($msg)); echo "OK\n"; echo "Reading Backinformatin:\n\n"; while ($out = socket_read($socket, 2048)) { echo $out." out\n"; } echo "Close socket........\n"; //socket_close($socket); echo "OK,He He.\n\n";

WebSocket JWT令牌连接授权

<div class="post-text" itemprop="text"> <p>I am trying to make a websocket connection to a URL(python client) which needs to have a jwt token passed in and the server(implemented in GO) listens to this request on and is supposed to authenticate by parsing the token.</p> <p>I try to use this part of the code to make the request - </p> <pre><code>def test_auth_token(token) conn = create_connection("ws://&lt;IP&gt;:port"+ '/'+ container.uuid + '?token='+token) result = conn.recv() assert result is not None </code></pre> <p>This request hits the server which runs this code to validate this request</p> <p>func ParseFromRequest(req *http.Request, keyFunc Keyfunc) (token *Token, err error) {</p> <pre><code>// Look for an Authorization header if ah := req.Header.Get("Authorization"); ah != "" { // Should be a bearer token if len(ah) &gt; 6 &amp;&amp; strings.ToUpper(ah[0:6]) == "BEARER" { return Parse(ah[7:], keyFunc) } } // Look for "access_token" parameter req.ParseMultipartForm(10e6) if tokStr := req.Form.Get("access_token"); tokStr != "" { return Parse(tokStr, keyFunc) } return nil, ErrNoTokenInRequest </code></pre> <p>}</p> <p>Every time, I am getting the "ErrNoTokenInRequest" output despite I am passing the token as a query parameter. The server side token validation is being done by this external library which contains the above GO Routine - <a href="https://github.com/dgrijalva/jwt-go/blob/master/jwt.go" rel="nofollow">https://github.com/dgrijalva/jwt-go/blob/master/jwt.go</a></p> <p>I am not sure, what could be the possible reasons that server doesn't find the token sent in my client? Is it supposed to be sent as payload or headers or something else? Could someone point to get this module working?</p> <p>With "access_token" as query parameter i get this exception - </p> <pre><code>self = &lt;websocket._core.WebSocket object at 0x10a15a6d0&gt; host = 'x.x.x.x.', port = 9345 resource = '/v1/stats/fff51e85-f2bb-4ace-8dcc-fde590932cca?access_token=eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MjIxMzEyMzUsInN1YiI6ImNh...vxvBmtZRrUTY5AcvrjbojXqLxFHL_CMsmTZfTXhOiy-7W2V95bqts2Wy4R8oQvsfDylYJWCBTzZNKHvPVFpcl0jQKLm1ms-LOJg1w-k23VfojZucPGtY5A' options = {} headers = ['GET /v1/stats/fff51e85-f2bb-4ace-8dcc-fde590932cca?access_token=eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MjIxMzEyMzUsInN1YiI... 'Host: x.x.x.x.:9345', 'Origin: http://x.x.x.x.:9345', 'Sec-WebSocket-Key: BN1n2BcCT/CUGh9MHeyL5g==', ...] key = 'BN1n2BcCT/CUGh9MHeyL5g==' header_str = 'GET /v1/stats/fff51e85-f2bb-4ace-8dcc-fde590932cca?access_token=eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MjIxMzEyMzUsInN1YiI6...3:9345 Origin: http://192.168.59.103:9345 Sec-WebSocket-Key: BN1n2BcCT/CUGh9MHeyL5g== Sec-WebSocket-Version: 13 </code></pre> </div>

pyhon服务器如何用websocke实现服务器和html5的通信(代码已实现成功连接客户端服务端)?

服务端代码 #coding=gbk #coding=utf-8 #-*- coding: UTF-8 -* import struct import socket import re import time #ws握手响应头 import hashlib import base64 from multiprocessing import Process #HTML_ROOT_DIR = r"C:\Users\lenovo\Desktop\html" def write_msg(message): data=struct.pack('B',129)#写入第一个字节 msg_len=len(message)#写入包长度 if(msg_len<=125): data+=struct.pack('B',msg_len) elif(mas_len<=2**16-1): data+=struct.pack('!BH',126,msg_len) elif(mas_len<=2**64-1): data+=struct.pack('!BQ',127,msg_len) else: pass data+=bytes(message,encoding="utf-8") return data def handle_client(client_socket): """ 处理客户端请求 """ # 获取客户端请求数据 #获得key request_data = client_socket.recv(1024) print(request_data) webpage_regex=re.compile('''.*Sec-WebSocket-Key:(.*)''',re.IGNORECASE) key=webpage_regex.findall(request_data.decode("utf-8")) keyy='' try: print(key[0]) keyy=key[0] keyy=keyy.strip() print(keyy) except: pass # 打开文件,读取内容 try: file = open(r"C:\html\shouji\测试\客户端原生socket.html", "rb") except IOError: response_start_line = "HTTP/1.1 404 Not Found\r\n" response_headers = "Server: My server\r\n" response_body = "The file is not found!" response = response_start_line + response_headers + "\r\n" + response_body client_socket.send(bytes(response, "utf-8")) client_socket.close() else: file_data = file.read() file.close() if(keyy==''): response_start_line = "HTTP/1.1 200 OK\r\n" response_headers = "Server: My server\r\n" response_body = file_data.decode("utf-8") response = response_start_line + response_headers + "\r\n" + response_body client_socket.send(bytes(response, "utf-8")) client_socket.close() print('https响应已发送') else: magic = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' sha1 = hashlib.sha1() sha1.update((keyy+magic).encode("utf8")) keyy=base64.b64encode(sha1.digest()) print('dddddd',base64.b64encode(sha1.digest())) keyy=keyy.decode("utf8") print('***********************',keyy) response_start_line = "HTTP/1.1 101 Switching Protocols\r\n" response_headers = "Upgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept:"+keyy+"\r\n" response_body = file_data.decode("utf-8") response = response_start_line + response_headers + "\r\n" #+ response_body client_socket.send(bytes(response, "utf-8")) print('ws响应已发送') while(1): time.sleep(5) client_socket.send(bytes('dddd', "utf-8")) #client_socket.send( write_msg('www.baidu.com')) print('发送了一次') # 关闭客户端连接 #client_socket.close() if __name__ == "__main__": server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(("0.0.0.0", 8000)) server_socket.listen(128) while True: client_socket, client_address = server_socket.accept() print("[%s, %s]用户连接上了" % client_address) handle_client_process = Process(target=handle_client, args=(client_socket,)) handle_client_process.start() #client_socket.close() 客户端代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h2 id="t">史p 芬</h2> <script type="text/javascript" charset="utf-8"> var ws = new WebSocket("ws://127.0.0.1:8000/"); //document.write(Date()); ws.onopen = function(e) { // Check the protocol chosen by the server //console.log(echoSocket.protocol); alert('连接上了') document.write(Date()); //ws.send('已经连接') } // 接受文本消息的事件处理实例: ws.onmessage = function(e) { alert('接受到消息') if(typeof e.data === "string"){ console.log("String message received", e, e.data); } else { console.log("Other message received", e, e.data); } }; ws.onclose = function(e) { alert('连接关闭') console.log("Connection closed", e); }; </script> </body> </html>

ModuleNotFoundError: No module named 'websocket'报错如何解决

请教各位大神,ModuleNotFoundError: No module named 'websocket'报错要如何解决? 开发ide是pycharm,安装了如下的插件。 ![图片说明](https://img-ask.csdn.net/upload/202003/15/1584259990_899715.jpg) 报错如下: ![图片说明](https://img-ask.csdn.net/upload/202003/15/1584260055_674646.jpg) 请知道问题的大神指点一下。 谢谢。

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

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向客户端广播服务器端消息

<div class="post-text" itemprop="text"> <p>I am new to Golang, I am trying to a create a WebSocket server which will broadcast messages to the connected clients. The messages here will be generated from the server side(by creating a default client).</p> <p>Here is my client.go</p> <pre><code>c, _, err := websocket.DefaultDialer.Dial(u.String(), nil) if err != nil { log.Fatal("dial:", err) } defer c.Close() done := make(chan struct{}) new_chan := make(chan string) //defer new_chan.Stop() go func() { for { new_chan &lt;- "my message" } }() hub := newHub() go hub.run() client := &amp;Client{hub: hub, ws: c, send: make(chan []byte, 256)} for { select { case &lt;-done: return case t := &lt;-new_chan: err := c.WriteMessage(websocket.TextMessage, []byte(t)) if err != nil { log.Println("write:", err) return } log.Printf(t) client.hub.broadcast &lt;- bytes.TrimSpace(bytes.Replace([]byte(t), newline, space, -1)) } } </code></pre> <p>this function will generate the messages and try to broadcast to other clients.</p> <p>server.go will add the clients to the hub</p> <pre><code>func echo(w http.ResponseWriter, r *http.Request) { c, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Print("upgrade:", err) return } hub := newHub() go hub.run() client := &amp;Client{hub: hub, ws: c, send: make(chan []byte, 256)} client.hub.register &lt;- client go client.writePump() </code></pre> <p>writePump() here will listen to the client.send channel and broadcast messages Now the connected client's hub is different is from the hub of the client at the server. So when I try to send messages, I am not receiving anything. How can I make it belong to the same hub(context)?</p> </div>

通过websocket将kubernetes日志公开到浏览器

<div class="post-text" itemprop="text"> <p>I am trying to use sidecar mode in kubernetes to create a logs sidecar to expose specific container logs. And I am using kubernetes client to fetch logs from kubernetes api and send it out by websocket. The code shows below:</p> <pre><code>func serveWs(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") conn, err := upgrader.Upgrade(w, r, nil) if err != nil { if _, ok := err.(websocket.HandshakeError); !ok { log.Println(err) } return } defer conn.Close() logsClient, err := InitKubeLogsClient(config.InCluster) if err != nil { log.Fatalln(err) } stream, err := logsClient.GetLogs(config.Namespace, config.PodName, config.ContainerName) if err != nil { log.Fatalln(err) } defer stream.Close() reader := bufio.NewReader(stream) for { line, err := reader.ReadString(' ') if err != nil { log.Fatalln(err) } conn.WriteMessage(websocket.TextMessage, []byte(line)) } } </code></pre> <p>I am using <a href="https://github.com/gorilla/websocket" rel="nofollow noreferrer">https://github.com/gorilla/websocket</a> as the websocket lib. And on the browser</p> <p>Is this the best way to do what I want? Is there some better way to just expose the logs api from k8s to websocket?</p> </div>

转到Websocket服务器与Python高速公路客户端冲突

<div class="post-text" itemprop="text"> <p>I have been successfully writing a Go (server) websocket 'chat' application based in <a href="http://gary.beagledreams.com/page/go-websocket-chat.html" rel="nofollow">this</a> example code </p> <p>Both client and server work as expected.</p> <p>When I have come to implement a client using Python's Autobahn I am running into trouble. it is based on <a href="https://github.com/tavendo/AutobahnPython/blob/master/examples/websocket/echo/client.py" rel="nofollow">this</a> example</p> <p>ws://localhost:8080/ws (which works in Chrome) yields an HTTP 1.0/400 from the server. ws://localhost:8080/ (does not work in Chrome) yields an HTTP 1.0/200 from the server (in both cases).</p> <p>Scanning the source (I admit, I don't know the WS protocol) seems to imply that the server should be responding with a 101.</p> <p>This is the output from Autobahn:</p> <pre><code>2013-05-19 15:33:10+0100 [Uninitialized] connection to 127.0.0.1:8080 established 2013-05-19 15:33:10+0100 [Uninitialized] GET /ws HTTP/1.1 User-Agent: AutobahnPython/0.5.14 Host: localhost:8080 Upgrade: WebSocket Connection: Upgrade Pragma: no-cache Cache-Control: no-cache Sec-WebSocket-Key: ZCnYpz0fvahS10S9aQWyvA== Sec-WebSocket-Version: 8 2013-05-19 15:33:10+0100 [Uninitialized] TX Octets to 127.0.0.1:8080 : sync = False, octets = 474554202f777320485454502f312e310d0a557365722d4167656e743a204175746f6261686e507974686f6e2f302e352e31340d0a486f73743a206c6f63616c686f73743a383038300d0a557067726164653a20576562536f636b65740d0a436f6e6e656374696f6e3a20557067726164650d0a507261676d613a206e6f2d63616368650d0a43616368652d436f6e74726f6c3a206e6f2d63616368650d0a5365632d576562536f636b65742d4b65793a205a436e59707a306676616853313053396151577976413d3d0d0a5365632d576562536f636b65742d56657273696f6e3a20380d0a0d0a 2013-05-19 15:33:10+0100 [EchoClientProtocol,client] RX Octets from 127.0.0.1:8080 : octets = 485454502f312e31203430302042616420526571756573740d0a0d0a7061727365203a20656d7074792075726c 2013-05-19 15:33:10+0100 [EchoClientProtocol,client] received HTTP response: HTTP/1.1 400 Bad Request 2013-05-19 15:33:10+0100 [EchoClientProtocol,client] received HTTP status line in opening handshake : HTTP/1.1 400 Bad Request 2013-05-19 15:33:10+0100 [EchoClientProtocol,client] received HTTP headers in opening handshake : {} 2013-05-19 15:33:10+0100 [EchoClientProtocol,client] failing WebSockets opening handshake ('WebSockets connection upgrade failed (400 - BadRequest)') 2013-05-19 15:33:10+0100 [EchoClientProtocol,client] dropping connection 2013-05-19 15:33:10+0100 [-] WebSocketProtocol.onClose: wasClean=False code=1006 reason=connection was closed uncleanly (None) self.closedByMe=False self.failedByMe=False self.droppedByMe=True self.wasClean=False self.wasNotCleanReason=None self.localCloseCode=None self.localCloseReason=None self.remoteCloseCode=None self.remoteCloseReason=None </code></pre> <p>UPDATE: I have also tried against <a href="https://groups.google.com/d/msg/golang-nuts/Yslt2GhHXiU/ZUNzswkNS7wJ" rel="nofollow">this</a> sample Go code which is a very trivial echo server. This makes me even more suspicious of my Autobahn code.</p> <p>UPDATE: Code, as requested:</p> <pre><code>package main import ( "net/http" "io" "code.google.com/p/go.net/websocket" ) func EchoServer(ws *websocket.Conn) { io.Copy(ws, ws); } func main() { http.Handle("/ws", websocket.Handler(EchoServer)); err := http.ListenAndServe(":8080", nil); if err != nil { panic("ListenAndServe: " + err.Error()) } } </code></pre> </div>

来自客户端的简单Websocket连接示例

<div class="post-text" itemprop="text"> <p>I would like to rewrite this JavaScript (run in Node) into Go.</p> <pre><code>let io = require('socket.io-client'); let socket = io('http://botws.generals.io'); socket.on('connect', function() { console.log('Connected to server.'); }); </code></pre> <p>(<em>I've tried <a href="https://github.com/graarh/golang-socketio" rel="nofollow noreferrer">this library</a> unsuccessfully; I can elaborate on my noob attempts if that helps</em>)</p> </div>

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

<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://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>

python的socket UDP 断开,重连问题

我使用socket模块,刚开始server和client都能发送和接受数据,但等待一段时间后 server能发送数据,但client显示没接受到数据,这应该是client断开连接,请教下该怎么 重新连接server?

如何通过WebSocket获取Docker容器输出?

<div class="post-text" itemprop="text"> <p><br> I am trying to send output from a docker container to the console using <code>fmt</code>, but when trying to do it i get this.<br></p> <pre><code>&amp;{0xc0422a65c0 {0 0} false &lt;nil&gt; 0x6415a0 0x641540} </code></pre> <p>How do I do this? This is my full code.</p> <pre><code>func main() { imageName := "hidden/hidden" ctx := context.Background() cli, err := client.NewClient("tcp://0.0.0.0:0000", "v0.00", nil, nil) if err != nil { panic(err) } fmt.Println("Pulling \"" + imageName + "\"") _, err = cli.ImagePull(ctx, imageName, types.ImagePullOptions{}) if err != nil { panic(err) } containerConfig := &amp;container.Config{ Image: imageName, Cmd: []string{"./app/start.sh", "--no-wizard"}, } resp, err := cli.ContainerCreate(ctx, containerConfig, nil, nil, "") if err != nil { panic(err) } if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil { panic(err) } timer := time.NewTimer(time.Minute) go func() { &lt;-timer.C if err := cli.ContainerStop(ctx, resp.ID, nil); err != nil { panic(err) } }() out, err := cli.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ShowStdout: true, ShowStderr: true, Follow: true}) if err != nil { panic(err) } io.Copy(os.Stdout, out) // This is what I want to change to print with "fmt". } </code></pre> <p>Tried: (but does not display until container is done.)</p> <pre><code>buf := new(bytes.Buffer) buf.ReadFrom(out) fmt.Println(buf.String()) </code></pre> <p><strong>Intention:</strong> Allow real-time console output to the web.</p> </div>

HTTP回调URL与WebSocket进行异步响应?

<div class="post-text" itemprop="text"> <p>I have two servers: Golang and Python (2.7). The Python (Bottle) server has a computation intensive task to perform and exposes a RESTful URI to start the execution of the process. That is, the Go server sends: </p> <p><code>HTTP GET to myserver.com/data</code></p> <p>The python server performs the computation and needs to inform the Go server of the completion of the processing. There are two ways in which I see this can be designed:</p> <ol> <li><p>Go sends a callback URL/data to Python and python responds by hitting that URL. E.g:<br></p> <p>HTTP GET | myserver.com/data | Data{callbackURI:goserver.com/process/results, Type: POST, response:"processComplete"}</p></li> <li><p>Have a WebSocket based response be sent back from Python to Go.</p></li> </ol> <p>What would be a more suitable design? Are there pros/cons of doing one over the other? Other than error conditions (server crashed etc.,) the only thing that the Python server needs to actually "inform" the client is about completing the computation. That's the only response.</p> <p>The team working on the Go server is not very well versed with having a Go client based on websockets/ajax (nor do I. But I've never written a single line of Go :) #1 seems to be easier but am not aware of whether it is an accepted design approach or is it just a hack? What's the recommended way to proceed in this regard?</p> </div>

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

发送连接升级后,如何将客户端http连接升级到golang中的websockets

<div class="post-text" itemprop="text"> <p>I need a golang client that can upgrade from an http get response to a websocket connection.</p> <p>I have a JS client that works and I've seen direct ws client connections but I have to upgrade from http. I have tried looking for other 3GL solutions (Java, C#, Python) but I need to be able to implement the upgrade in Go. I have seen Dart detaching the socket and creating a websocket from it.</p> <pre><code>WebSocket.fromUpgradedSocket </code></pre> <p>I noticed <a href="https://github.com/golang/go/issues/28030" rel="nofollow noreferrer">Client does not support Hijack</a> but the discussion didn't get me anywhere. I am using github.com/gorilla/websocket but can change that if it helps.</p> <p>Server:</p> <pre><code> func main() { srv := Srv{} count = 0 http.HandleFunc("/", srv.handleRoot) http.HandleFunc("/ws", srv.handleWs) log.Fatal(http.ListenAndServe(":5002", nil)) } func (tool *Srv) handleRoot(w http.ResponseWriter, r *http.Request) { webSocketKey := hdr.Get("Sec-WebSocket-Key") log.Printf("Socket key = '%v'", webSocketKey) secWsAccept := computeAcceptKey(webSocketKey) log.Printf("Accept = '%v'", secWsAccept) w.Header().Add("sec-websocket-accept", secWsAccept) w.Header().Add("upgrade", "websockt") w.Header().Add("connection", "upgrade") w.WriteHeader(101) } func (tool *Srv) handleWs(w http.ResponseWriter, r *http.Request) { var upgrader = websocket.Upgrader{} conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Fatalf("Websocket fatal error. %v", err) } tool.conn = conn go tool.serviceWsRequests() } func (tool *Srv) serviceWsRequests() { for { log.Printf("starting ws") req := request{} err := tool.conn.ReadJSON(&amp;req) if err != nil { log.Printf("Failed to decode ws message. %v", err) break } fmt.Printf("Got request. %v ", req) if req.Method == "ping" { fmt.Printf("Param=%v ", req.Parameters) } } } var keyGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11") func computeAcceptKey(challengeKey string) string { h := sha1.New() h.Write([]byte(challengeKey)) h.Write(keyGUID) return base64.StdEncoding.EncodeToString(h.Sum(nil)) } </code></pre> <p>Client:</p> <pre><code> func main() { tr := &amp;http.Transport{ MaxIdleConns: 10, IdleConnTimeout: 30 * time.Second, DisableCompression: true, } client := &amp;http.Client{ Transport: tr, // Do NOT follow redirects CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, } wsKey, err := generateKey() if err != nil { log.Printf("Cannot generate challenge key %v", err) } // Get request for ws upgrade. req, err := http.NewRequest("GET", "http://localhost:5002", nil) req.Header.Add("Connection", "Upgrade") req.Header.Add("Upgrade", "websocket") req.Header.Add("Sec-WebSocket-Version", "13") req.Header.Add("Sec-WebSocket-Key", wsKey) log.Printf("ws key '%v'", wsKey) resp, err := client.Do(req) if err != nil { log.Printf("Get error %v", err) } defer func() { if resp != nil { err = resp.Body.Close() } }() log.Printf("Status='%v', proto='%v'", resp.Status, resp.Proto) body, err := ioutil.ReadAll(resp.Body) hdr := resp.Header for k, v := range hdr{ log.Printf("%v : %v", k, v) } log.Printf("Body = %v", string(body)) resp, err = http.Get("ws://localhost:5002/ws") if err != nil { log.Printf("Error '%v'", err) } } func generateKey() (string, error) { p := make([]byte, 16) if _, err := io.ReadFull(rand.Reader, p); err != nil { return "", err } return base64.StdEncoding.EncodeToString(p), nil } var keyGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11") func computeAcceptKey(challengeKey string) string { h := sha1.New() h.Write([]byte(challengeKey)) h.Write(keyGUID) return base64.StdEncoding.EncodeToString(h.Sum(nil)) } </code></pre> <p>I get an error </p> <pre><code>Error 'Get ws://localhost:5002/ws: unsupported protocol scheme "ws"' </code></pre> <p>Which doesn't surprise me because I haven't upgraded the connection. So how do I go an upgrade in Go?</p> </div>

将golang与大猩猩websocket库一起使用,为什么WriteJson返回错误?

<div class="post-text" itemprop="text"> <p>I'm following the instructions here:</p> <p><a href="https://testnet.bitmex.com/app/wsAPI" rel="nofollow noreferrer">https://testnet.bitmex.com/app/wsAPI</a></p> <p>and I've confirmed that the following Python implementation works (ie no network issues etc from my end) because: </p> <pre><code>python wsdump.py \ wss://testnet.bitmex.com/realtime &gt; {"op":"subscribe","args":["orderBookL2_25:XBTUSD"]} </code></pre> <p>results in</p> <pre><code>{"success":true,"subscribe":"orderBookL2_25:XBTUSD","request":{"op":"subscribe","args":["orderBookL2_25:XBTUSD"]}} </code></pre> <p>I've tried to modify the gorilla sample code to put together a basic client:</p> <pre><code>package main import ( "encoding/json" "flag" "fmt" "log" "net/url" "os" "os/signal" "time" "github.com/gorilla/websocket" ) var addr = flag.String("addr", "testnet.bitmex.com", "http service address") func main() { flag.Parse() log.SetFlags(0) interrupt := make(chan os.Signal, 1) signal.Notify(interrupt, os.Interrupt) u := url.URL{Scheme: "wss", Host: *addr, Path: "/realtime"} log.Printf("connecting to %s", u.String()) c, _, err := websocket.DefaultDialer.Dial(u.String(), nil) if err != nil { log.Fatal("dial:", err) } defer c.Close() done := make(chan struct{}) go func() { defer close(done) for { _, message, err := c.ReadMessage() if err != nil { log.Println("read:", err) return } log.Printf("recv: %s", message) } }() type commandStruct struct { Op string `json:"op"` Args []string `json:"args"` } command := &amp;commandStruct{ Op: "subscribe", Args: []string{"orderBookL2_25:XBTUSD"}} json, _ := json.Marshal(command) stringJSON := string(json) fmt.Println("JSON:", stringJSON) connectionErr := c.WriteJSON(stringJSON) if connectionErr != nil { log.Println("write:", connectionErr) } for { select { case &lt;-done: return case &lt;-interrupt: log.Println("interrupt") // Cleanly close the connection by sending a close message and then // waiting (with timeout) for the server to close the connection. err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) if err != nil { log.Println("write close:", err) return } select { case &lt;-done: case &lt;-time.After(time.Second): } return } } } </code></pre> <p>My program prints the following to the console:</p> <pre><code>{"op":"subscribe","args":["orderBookL2_25:XBTUSD"]} </code></pre> <p>which is identical to the JSON in the Python example above. But then I get an error message:</p> <pre><code>recv: {"status":400,"error":"Unrecognized request. See the docs or send 'help' for more details.","meta":{},"request":"{\"op\":\"subscribe\",\"args\":[\"orderBookL2_25:XBTUSD\"]}"} </code></pre> <p>Why do I get a different result?</p> </div>

django➕dwebsocket➕nginx报错301怎么解决?

最近在做网站的站内消息,使用的django➕dwebsocket➕nginx 但是在上到服务器的时候,访问建立连接的函数,报错301永久重定向了,我nginx也配置了。但是就是连接不上。 ``` nginx配置如下 server { listen 80 default_server; listen [::]:80 default_server; server_name _; # gzip config gzip on; gzip_min_length 1k; gzip_comp_level 9; gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png; gzip_vary on; gzip_disable "MSIE [1-6]\."; root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location /api { rewrite ^/api/(.*)$ /$1 break; proxy_pass http://39.97.166.114:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_connect_timeout 60; proxy_read_timeout 600; proxy_send_timeout 600; } ``` ``` 后台代码 clients = [] @accept_websocket def echo(request): if request.is_websocket: try: clients.append(request.websocket) print(clients) for message in request.websocket: print(message) me = eval(message) # 将字符串类型的消息转换为字典型 print(type(me)) print(me["name"]) me['id']=1 me['username']=2 print(me) # print(request.websocket.count_messages()) if not message: break for client in clients: # print(client.count_messages()) print(client) # print(client.has_messages()) client.send(message) finally: clients.remove(request.websocket) ``` ``` 前端代码 <!DOCTYPE html> <html> <head> <title>django-websocket</title> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script type="text/javascript">//<![CDATA[ $(function () { //创建WebSocket对象获得连接 $('#connect_websocket').click(function () { if(window.websocket){ window.websocket.close() } var websocket = new WebSocket("ws://saas111.com/api/user/echo"); websocket.onopen = function () { console.log('WebSocket open'); }; websocket.onmessage = function (responseData) { console.log('message: ' + responseData.data);//浏览器控制台打印返回的数据 var jsondata = eval('(' + responseData.data + ')'); //将返回的数据转换为json对象 $('#messagecontainer').prepend('<p>' + jsondata.name + '</p>'); //展示数据 }; window.websocket = websocket; }); //发送消息 $('#send_message').click(function () { if(!window.websocket){ alert("Please connect server."); }else{ {# window.s.send($('#message').val());#} //发送字符串数据类型 window.websocket.send(JSON.stringify({"name":$('#message').val()}));//发送json数据类型 } }); //关闭websocket连接 $('#close_websocket').click(function () { if(window.websocket){ window.websocket.close(); } }); }); //]]></script> </head> <body> <br> <input type="text" id="message" value="Hello, World!" /> <button type="button" id="connect_websocket">连接websocket</button> <button type="button" id="send_message">发送消息</button> <button type="button" id="close_websocket">关闭websocket</button> <h1>接收消息</h1> <div id="messagecontainer"> </div> </body> </html> ```

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

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

在中国程序员是青春饭吗?

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

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

String s = new String(" a ") 到底产生几个对象?

老生常谈的一个梗,到2020了还在争论,你们一天天的,哎哎哎,我不是针对你一个,我是说在座的各位都是人才! 上图红色的这3个箭头,对于通过new产生一个字符串(”宜春”)时,会先去常量池中查找是否已经有了”宜春”对象,如果没有则在常量池中创建一个此字符串对象,然后堆中再创建一个常量池中此”宜春”对象的拷贝对象。 也就是说准确答案是产生了一个或两个对象,如果常量池中原来没有 ”宜春” ,就是两个。...

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

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

Linux面试题(2020最新版)

文章目录Linux 概述什么是LinuxUnix和Linux有什么区别?什么是 Linux 内核?Linux的基本组件是什么?Linux 的体系结构BASH和DOS之间的基本区别是什么?Linux 开机启动过程?Linux系统缺省的运行级别?Linux 使用的进程间通信方式?Linux 有哪些系统日志文件?Linux系统安装多个桌面环境有帮助吗?什么是交换空间?什么是root帐户什么是LILO?什...

Linux命令学习神器!命令看不懂直接给你解释!

大家都知道,Linux 系统有非常多的命令,而且每个命令又有非常多的用法,想要全部记住所有命令的所有用法,恐怕是一件不可能完成的任务。 一般情况下,我们学习一个命令时,要么直接百度去搜索它的用法,要么就直接用 man 命令去查看守冗长的帮助手册。这两个都可以实现我们的目标,但有没有更简便的方式呢? 答案是必须有的!今天给大家推荐一款有趣而实用学习神器 — kmdr,让你解锁 Linux 学习新姿势...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

史上最全的 python 基础知识汇总篇,没有比这再全面的了,建议收藏

网友们有福了,小编终于把基础篇的内容全部涉略了一遍,这是一篇关于基础知识的汇总的文章,请朋友们收下,不用客气,不过文章篇幅肯能会有点长,耐心阅读吧爬虫(七十)多进程multiproces...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

85后蒋凡:28岁实现财务自由、34岁成为阿里万亿电商帝国双掌门,他的人生底层逻辑是什么?...

蒋凡是何许人也? 2017年12月27日,在入职4年时间里,蒋凡开挂般坐上了淘宝总裁位置。 为此,时任阿里CEO张勇在任命书中力赞: 蒋凡加入阿里,始终保持创业者的冲劲,有敏锐的...

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

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

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

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

新一代神器STM32CubeMonitor介绍、下载、安装和使用教程

关注、星标公众号,不错过精彩内容作者:黄工公众号:strongerHuang最近ST官网悄悄新上线了一款比较强大的工具:STM32CubeMonitor V1.0.0。经过我研究和使用之...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

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

大学一路走来,学习互联网全靠这几个网站,最终拿下了一把offer

大佬原来都是这样炼成的

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

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

为什么你不想学习?只想玩?人是如何一步一步废掉的

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

什么时候跳槽,为什么离职,你想好了么?

都是出来打工的,多为自己着想

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

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

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

你期望月薪4万,出门右拐,不送,这几个点,你也就是个初级的水平

先来看几个问题通过注解的方式注入依赖对象,介绍一下你知道的几种方式@Autowired和@Resource有何区别说一下@Autowired查找候选者的...

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

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

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

立即提问
相关内容推荐