Gorilla WebSocket与golang.org/x/net/websocket的比较

根据 Gorilla Websockets项目,无法使用 golang.org/x/net/websocket </ strong>发送ping和pong。 同时,以下内容在 golang.org/x/net/的项目页面上 websocket :</ p>

软件包websocket为RFC 6455中指定的WebSocket协议实现了客户端和服务器。</ p>
</ blockquote> \ n

我有点困惑。 golang.org/x/net/websocket </ strong>实现RFC 6455,但是尽管在 RFC 6455-部分控制框架 </ p>

所以,如果我使用 golang.org / x / net / websocket </ strong>软件包。 超时后连接会中止吗? 换句话说,在这里如何确保连接不会中断。</ p>
</ div>



According Gorilla Websockets Project it is not possible to send pings and pongs using golang.org/x/net/websocket. At the same time, the following is on the project page of golang.org/x/net/websocket:

Package websocket implements a client and server for the WebSocket protocol as specified in RFC 6455.

I am a little confused. golang.org/x/net/websocket implements RFC 6455 but can not send control frames (cancel, ping, pong) although this is specified in RFC 6455 - Section Control Frames

So what will happen if I use golang.org/x/net/websocket package. Will the connection abort after a timeout? In other words, how is it ensured here that the connection does not break off.


根据大猩猩Websockets项目,无法使用golang.org/x/net/websocket发送ping和pong </ p>
</ blockquote>

Gorilla自述文件有所不同。 它说golang.org/x/net软件包不能发送ping </ em>或接收pong </ em>。 并不是说该软件包不会发送Pong。</ p>

golang.org/x/net软件包会通过将Pong发送给对等方来自动响应从对等方收到的ping, 和大猩猩包一样。 这两个软件包都可以与使用ping和pongs的对等方正常工作,以保持连接状态。</ p>

使用golang.org/x/net/websocket软件包的应用程序不能使用pings和pongs 使连接保持活动状态。 无法发送ping。 无法检测到已收到乒乓球。</ p>
</ div>



According Gorilla Websockets Project it is not possible to send pings and pongs using golang.org/x/net/websocket

The Gorilla README says something different. It says that the golang.org/x/net package cannot send a ping or receive a pong. It does not say that the package will not send a pong.

The golang.org/x/net package automatically responds to a ping received from the peer by sending a pong to the peer, as does the Gorilla package. Both packages work correctly with a peer that's using ping and pongs to keep the connection alive.

An application that uses the golang.org/x/net/websocket package cannot employ pings and pongs to keep the connection alive. There's no way to send the ping. There's no way to detect that the pong was received.

Csdn user default icon
如何使用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>

带有Web代理的Golang Gorilla Websocket

<div class="post-text" itemprop="text"> <p>I'm working on a POC using Gorilla/Websocket to communicate, through a Web Proxy, with the Websocket Check Website "echo.websocket.org".</p> <p>I'm using the free online Proxy "hide.me/en/" for testing.</p> <p>When I simply try to communicate with "echo.websocket.org" (Server side), my client-site Websocket POC reach the response.</p> <p>But when i try to add the Proxy gesture, everything goes wrong :(</p> <p>Here is a sample of my code :</p> <pre><code>package main import ( "flag" "log" "net/url" "os" "os/signal" "time" "github.com/gorilla/websocket" "net/http" ) var addrWebsocket = flag.String("addrWebsocket", "echo.websocket.org", "http service address") func main() { flag.Parse() log.SetFlags(0) interrupt := make(chan os.Signal, 1) signal.Notify(interrupt, os.Interrupt) //Initialize the WebSocket URL and the Path to follow uWS := url.URL{Scheme: "wss", Host: *addrWebsocket} //Initialize the Proxy URL and the Path to follow uProxy, _ := url.Parse("https://hide.me/en/proxy") //Set the Dialer (especially the proxy) dialer := websocket.Dialer{ Proxy: http.ProxyURL(uProxy), } //dialer := websocket.DefaultDialer ==&gt; with this default dialer, it works ! c, _, err := dialer.Dial(uWS.String(), nil) // ==&gt; With the proxy config, it fails here ! defer c.Close() done := make(chan struct{}) go func() { defer c.Close() defer close(done) for { _, message, err := c.ReadMessage() if err != nil { log.Println("read:", err) return } log.Printf("recv: %s", message) } }() ticker := time.NewTicker(time.Second) defer ticker.Stop() for { select { case t := &lt;-ticker.C: err := c.WriteMessage(websocket.TextMessage, []byte(t.String())) if err != nil { log.Println("write:", err) return } case &lt;-interrupt: log.Println("interrupt") 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): } c.Close() return } } } </code></pre> <p>I'm a very beginner in Go so don't hesitate to correct me if my code un not clear and clean.</p> <p>Thanks for your help !</p> </div>

调用`go get`时缺少Git命令

<div class="post-text" itemprop="text"> <p>My Dockerfile</p> <pre><code>FROM golang:1.10.2-alpine3.7 AS build RUN apk --no-cache add gcc g++ make ca-certificates RUN apk add git WORKDIR /go/src/github.com/meower COPY Gopkg.lock Gopkg.toml ./ COPY util util COPY event event COPY db db COPY search search COPY schema schema COPY meow-service meow-service COPY query-service query-service COPY pusher-service pusher-service RUN go get -d -v ./... RUN go install ./... FROM alpine:3.7 WORKDIR /usr/bin COPY --from=build /go/bin . </code></pre> <p>I added apk add git line.Without this line my docker-compose up produced</p> <pre><code>Step 13/17 : RUN go get -d -v ./... ---&gt; Running in d917adba00cd github.com/lib/pq (download) go: missing Git command. See https://golang.org/s/gogetcmd package github.com/lib/pq: exec: "git": executable file not found in $PATH github.com/nats-io/go-nats (download) go: missing Git command. See https://golang.org/s/gogetcmd package github.com/nats-io/go-nats: exec: "git": executable file not found in $PATH github.com/gorilla/mux (download) go: missing Git command. See https://golang.org/s/gogetcmd package github.com/gorilla/mux: exec: "git": executable file not found in $PATH github.com/kelseyhightower/envconfig (download) go: missing Git command. See https://golang.org/s/gogetcmd package github.com/kelseyhightower/envconfig: exec: "git": executable file not found in $PATH package github.com/retry: invalid github.com/ import path "github.com/retry" github.com/segmentio/ksuid (download) go: missing Git command. See https://golang.org/s/gogetcmd package github.com/segmentio/ksuid: exec: "git": executable file not found in $PATH github.com/gorilla/websocket (download) go: missing Git command. See https://golang.org/s/gogetcmd package github.com/gorilla/websocket: exec: "git": executable file not found in $PATH github.com/olivere/elastic (download) go: missing Git command. See https://golang.org/s/gogetcmd package github.com/olivere/elastic: exec: "git": executable file not found in $PATH </code></pre> <p>With git line,other problems are still there</p> <pre><code>docker-compose up Building pusher Step 1/18 : FROM golang:1.10.2-alpine3.7 AS build ---&gt; 44ccce322b34 Step 2/18 : RUN apk --no-cache add gcc g++ make ca-certificates ---&gt; Using cache ---&gt; 088fa5ba19a9 Step 3/18 : RUN apk add git ---&gt; Running in 01022f57861b WARNING: Ignoring APKINDEX.70c88391.tar.gz: No such file or directory WARNING: Ignoring APKINDEX.5022a8a2.tar.gz: No such file or directory ERROR: unsatisfiable constraints: git (missing): </code></pre> <p>What does this mean?</p> </div>

使用Golang的gorilla / websocket软件包的Websocket连接断开

<div class="post-text" itemprop="text"> <p>I'm attempting to port a NodeJS script that establishes and maintains a Websocket connection to a third-party server to Go using the <a href="https://github.com/gorilla/websocket" rel="nofollow noreferrer">gorilla/websocket</a> package. In the <a href="https://gist.github.com/anonymous/7c169e995d13a943d3f494c88cac7a17" rel="nofollow noreferrer">Node script</a>, a pong is received following a ping, and the connection is kept alive indefinitely. In the <a href="https://gist.github.com/anonymous/69b8dca0172803fccb45dfeb5d310133" rel="nofollow noreferrer">Go script</a>, ping/pong works but the connection is dropped by the server after about 30 seconds. </p> <p>I suspect that the pings that are sent using the Go websocket package are malformed, but I can't pinpoint the cause of this. Comparing the captured, encrypted network traffic while running these programs shows no difference in the response length of the TCP requests and responses, so this may not be the issue. Any help would be greatly appreciated!</p> <p><strong>websocket.js</strong></p> <pre><code>#!/usr/bin/env node // npm install websocket@1.0.25 --save const WebSocketClient = require('websocket').client; const client = new WebSocketClient(); let lastPing = new Date().getTime(); client.on('connectFailed', function(error) { console.log('Connect Error: ' + error.toString()); }); client.on('connect', function(connection) { console.log('Connected to Server...'); connection.on('error', function(error) { console.log("Connection Error: " + error.toString()); }); connection.on('close', function() { console.log('Connection Closed'); }); connection.on('message', function(message) { if (message.type === 'utf8') { console.log(message.utf8Data); } }); connection.on('pong', function(){ console.log('[pingpong] response took', (new Date().getTime() - lastPing) + 'ms'); }) function send(message) { if (connection.connected) { connection.sendUTF(message); } } // Send a ping every 10s // to keep the connection live setInterval(function(){ lastPing = new Date().getTime(); connection.ping(); }, 10000); }); client.connect('wss://ws.radarrelay.com/0x/v0/ws'); </code></pre> <p><strong>websocket.go</strong></p> <pre><code>package main import ( "flag" "log" "os" "os/signal" "time" "github.com/gorilla/websocket" ) var addr = "wss://api.radarrelay.com/0x/v0/ws" func main() { flag.Parse() log.SetFlags(0) timeoutDuration := 2 * time.Minute interrupt := make(chan os.Signal, 1) signal.Notify(interrupt, os.Interrupt) c, _, err := websocket.DefaultDialer.Dial(addr, nil) if err != nil { log.Fatal("dial:", err) } else { log.Println("Connected to server") } c.SetPongHandler(func(str string) error { log.Println("pong received", str) return nil }) defer c.Close() done := make(chan struct{}) go func() { defer c.Close() defer close(done) for { c.SetReadDeadline(time.Now().Add(timeoutDuration)) _, message, err := c.ReadMessage() if err != nil { log.Println("read:", err) return } if len(message) &gt;= 2 { message = message[2:] } log.Printf("recv: %s", message) } }() ticker := time.NewTicker(10 * time.Second) defer ticker.Stop() for { select { case _ = &lt;-ticker.C: err := c.WriteMessage(websocket.PingMessage, []byte{}) if err != nil { log.Println("write:", err) return } else { log.Println("ping sent") } case &lt;-interrupt: log.Println("interrupt") // To cleanly close a connection, a client should send a close // frame and wait 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): } c.Close() return } } } </code></pre> </div>

Gorilla WebSocket WriteMessage错误-Go Lang

<div class="post-text" itemprop="text"> <p>I am currently experimenting with Gorilla WebSocket package. When sending a message using <a href="https://godoc.org/github.com/gorilla/websocket#Conn.WriteMessage" rel="nofollow"><code>WriteMessage</code></a>, if an error is returned, what should I do? Should I start the <a href="https://tools.ietf.org/html/rfc6455#section-7.1.2" rel="nofollow">Closing Handshake</a> or assume that if there is a problem it will be caught using the <a href="https://godoc.org/github.com/gorilla/websocket#Conn.ReadMessage" rel="nofollow"><code>ReadMessage</code></a> method and simply log the error?</p> </div>

Golang Gorilla Websocket在120秒后停止接收信息

<div class="post-text" itemprop="text"> <p>I'm currently trying to connect to the CEX.IO bitcoin exchange's websocket, but have been having issues not only with CEX.IO but with others too. All of my connections drop around the 120-second mark which makes me think there is some TTL problem going on. The Process() goroutine in the main package ends up just hanging and waiting for data from the readLoop which just stops receiving data. I've included some read-only API keys in the code so you can test if you'd like.</p> <pre><code>package main import ( "fmt" "bitbucket.org/tradedefender/cryptocurrency/exchange-connector/cexio" "github.com/shopspring/decimal" "encoding/json" "time" ) type OrderBook struct { Asks []Ask Bids []Bid } type Ask struct { Rate decimal.Decimal Amount decimal.Decimal } type Bid struct { Rate decimal.Decimal Amount decimal.Decimal } func main() { cexioConn := new(cexio.Connection) err := cexioConn.Connect() if err != nil { fmt.Errorf("error: %s", err.Error()) } err = cexioConn.Authenticate("TLwYkktLf7Im6nqSKt6UO1IrU", "9ImOJcR7Qj3LMIyPCzky0D7WE") if err != nil { fmt.Errorf("error: %s", err.Error()) } readChannel := make(chan cexio.IntraAppMessage, 25) go cexioConn.ReadLoop(readChannel) processor := Processor{ WatchPairs: [][2]string{ [2]string{ "BTC", "USD", }, }, conn: cexioConn, } go processor.Process(readChannel) // LOL for { continue } } type Processor struct { WatchPairs [][2]string conn *cexio.Connection } func (p *Processor) Process(ch &lt;-chan cexio.IntraAppMessage) { p.conn.SubscribeToOrderBook(p.WatchPairs[0]) pingTimer := time.Now().Unix() for { fmt.Printf("(%v) ", time.Now().Unix()) if (time.Now().Unix() - pingTimer) &gt;= 10 { fmt.Println("sending ping") p.conn.SendPing() pingTimer = time.Now().Unix() } readMsg := &lt;- ch output, _ := json.Marshal(readMsg.SocketMessage) fmt.Println(string(output)) if readMsg.SocketMessage.Event == "ping" { fmt.Println("sending pong") p.conn.SendPong() pingTimer = time.Now().Unix() } } } </code></pre> <p>Below is the connector to the cexio websocket. Here is a link to their API: <a href="https://cex.io/websocket-api" rel="nofollow noreferrer">https://cex.io/websocket-api</a></p> <pre><code>package cexio import ( "github.com/gorilla/websocket" //"github.com/shopspring/decimal" "github.com/satori/go.uuid" "encoding/hex" "encoding/json" "crypto/hmac" "crypto/sha256" "bytes" "strconv" "time" "fmt" ) const Url = "wss://ws.cex.io/ws/" type Connection struct { conn *websocket.Conn } type IntraAppMessage struct { SocketMessage GenericMessage ProgramMessage ProgramMessage } type GenericMessage struct { Event string `json:"e"` Data interface{} `json:"data"` Auth AuthData `json:"auth,omitempty"` Ok string `json:"ok,omitempty"` Oid string `json:"oid,omitempty"` Time int64 `json:"time,omitempty"` } type ProgramMessage struct { Error string } type AuthData struct { Key string `json:"key"` Signature string `json:"signature"` Timestamp int64 `json:"timestamp"` } type OrderBookSubscribeData struct { Pair [2]string `json:"pair"` Subscribe bool `json:"subscribe"` Depth int `json:"depth"` } func (c *Connection) SendPong() error { pongMsg := GenericMessage{ Event: "pong", } err := c.conn.WriteJSON(pongMsg) if err != nil { return nil } deadline := time.Now().Add(15*time.Second) err = c.conn.WriteControl(websocket.PongMessage, nil, deadline) if err != nil { return err } return nil } func (c *Connection) SendPing() error { pingMsg := GenericMessage{ Event: "get-balance", Oid: uuid.NewV4().String(), } err := c.conn.WriteJSON(pingMsg) if err != nil { return err } deadline := time.Now().Add(15*time.Second) err = c.conn.WriteControl(websocket.PingMessage, nil, deadline) if err != nil { return err } return nil } func (c *Connection) Connect() error { dialer := *websocket.DefaultDialer wsConn, _, err := dialer.Dial(Url, nil) if err != nil { return err } c.conn = wsConn //c.conn.SetPingHandler(c.HandlePing) for { _, msgBytes, err := c.conn.ReadMessage() if err != nil { c.Disconnect() return err } fmt.Println(string(msgBytes)) var m GenericMessage err = json.Unmarshal(msgBytes, &amp;m) if err != nil { c.Disconnect() return err } if m.Event != "connected" { c.Disconnect() return err } else { break } } return nil } func (c *Connection) Disconnect() error { return c.conn.Close() } func (c *Connection) ReadLoop(ch chan&lt;- IntraAppMessage) { for { fmt.Println("starting new read") _, msgBytes, err := c.conn.ReadMessage() if err != nil { ch &lt;- IntraAppMessage{ ProgramMessage: ProgramMessage{ Error: err.Error(), }, } continue } var m GenericMessage err = json.Unmarshal(msgBytes, &amp;m) if err != nil { ch &lt;- IntraAppMessage{ ProgramMessage: ProgramMessage{ Error: err.Error(), }, } continue } ch &lt;- IntraAppMessage{ SocketMessage: m, } } } func CreateSignature(timestamp int64, key, secret string) string { secretBytes := []byte(secret) h := hmac.New(sha256.New, secretBytes) var buffer bytes.Buffer buffer.WriteString(strconv.FormatInt(timestamp, 10)) buffer.WriteString(key) h.Write(buffer.Bytes()) return hex.EncodeToString(h.Sum(nil)) } func (c *Connection) Authenticate(key, secret string) error { timestamp := time.Now().Unix() signature := CreateSignature(timestamp, key, secret) var authMsg GenericMessage authMsg.Event = "auth" authMsg.Auth = AuthData{ Key: key, Signature: signature, Timestamp: timestamp, } err := c.conn.WriteJSON(authMsg) if err != nil { return err } for { _, msgBytes, err := c.conn.ReadMessage() if err != nil { c.Disconnect() return err } fmt.Println(string(msgBytes)) var m GenericMessage err = json.Unmarshal(msgBytes, &amp;m) if err != nil { c.Disconnect() return err } if m.Event != "auth" &amp;&amp; m.Ok != "ok" { c.Disconnect() return err } else { break } } return nil } func (c *Connection) SubscribeToOrderBook(pair [2]string) error { sendMsg := GenericMessage{ Event: "order-book-subscribe", Data: OrderBookSubscribeData{ Pair: pair, Subscribe: true, Depth: 0, }, Oid: uuid.NewV4().String(), } err := c.conn.WriteJSON(sendMsg) if err != nil { return err } return nil } func (c *Connection) GetBalance() error { sendMsg := GenericMessage{ Event: "get-balance", Oid: uuid.NewV4().String(), } err := c.conn.WriteJSON(sendMsg) if err != nil { return err } return nil } </code></pre> </div>

使用错误的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>


<div class="post-text" itemprop="text"> <p>I have studied the Godoc of the gorilla/websocket package.</p> <p>In the Godoc it is clearly stated that</p> <blockquote> <p>Concurrency Connections support one concurrent reader and one concurrent writer.</p> <p>Applications are responsible for ensuring that no more than one goroutine calls the write methods (NextWriter, SetWriteDeadline, WriteMessage, WriteJSON, EnableWriteCompression, SetCompressionLevel) concurrently and that no more than one goroutine calls the read methods (NextReader, SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler, SetPingHandler) concurrently.</p> <p>The Close and WriteControl methods can be called concurrently with all other methods.</p> </blockquote> <p>However, in one of the example provided by the package</p> <pre><code>func (c *Conn) readPump() { defer func() { hub.unregister &lt;- c c.ws.Close() }() c.ws.SetReadLimit(maxMessageSize) c.ws.SetReadDeadline(time.Now().Add(pongWait)) c.ws.SetPongHandler(func(string) error { c.ws.SetReadDeadline(time.Now().Add(pongWait)); return nil }) for { _, message, err := c.ws.ReadMessage() if err != nil { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) { log.Printf("error: %v", err) } break } message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1)) hub.broadcast &lt;- message } } </code></pre> <p>Source: <a href="https://github.com/gorilla/websocket/blob/a68708917c6a4f06314ab4e52493cc61359c9d42/examples/chat/conn.go#L50" rel="nofollow noreferrer">https://github.com/gorilla/websocket/blob/a68708917c6a4f06314ab4e52493cc61359c9d42/examples/chat/conn.go#L50</a></p> <p>This line</p> <pre><code>c.ws.SetPongHandler(func(string) error { c.ws.SetReadDeadline(time.Now().Add(pongWait)); return nil }) </code></pre> <p>and this line</p> <pre><code>_, message, err := c.ws.ReadMessage() </code></pre> <p>seems to be not synchronized because the first line is a callback function so it should be invoked in a Goroutine created in the package and the second line is executing in the Goroutine that invoke <code>serveWs</code></p> <p>More importantly, how should I ensure that no more than one goroutine calls the <code>SetReadDeadline</code>, <code>ReadMessage</code>, <code>SetPongHandler</code>, <code>SetPingHandler</code> concurrently?</p> <p>I tries to use a Mutex lock and lock it whenever I call the above functions, and unlock it afterwards, but quickly I realize a problem. It is usual (also in the example) that <code>ReadMessage</code> is being called in a for-loop. But if the Mutext is locked before the ReadMessage, then no other Read-functions can acquire the lock and execute until next message is received</p> <p>Is there any better way in handling this concurrency issue? Thanks in advance.</p> </div>

一分钟后,Gorilla WebSocket断开连接

<div class="post-text" itemprop="text"> <p>I'm using Go (Golang) 1.4.2 with Gorilla WebSockets behind an nginx 1.4.6 reverse proxy. My WebSockets are disconnecting after about a minute of having the page open. Same behavior occurs on Chrome and Firefox.</p> <p>At first, I had problems connecting the server and client with WebSockets. Then, I read that I needed to tweak my nginx configuration. This is what I have.</p> <pre><code>server { listen 80; server_name example.com; proxy_pass_header Server; location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forward-Proto $scheme; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass; } } </code></pre> <p>My Go code is basically echoing back the client's message. (Errors omitted for brevity). This is my <code>HandleFunc</code>.</p> <pre><code>var up = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } ws, _ := up.Upgrade(resp, req, nil) defer ws.Close() var s struct { Foo string Bar string } for { ws.ReadJSON(&amp;s) ws.WriteJSON(s) } </code></pre> <p>The JavaScript is pretty simple as well.</p> <pre><code>var ws = new WebSocket("ws://example.com/ws/"); ws.addEventListener("message", function(evnt) { console.log(JSON.parse(evnt.data)); }); var s = { Foo: "hello", Bar: "world" }; ws.send(JSON.stringify(s)); </code></pre> <p>Go is reporting <code>websocket: close 1006 unexpected EOF</code>. I know that when I leave or refresh the page <code>ReadJSON</code> returns <code>EOF</code>, but this appears to be a different error. Also, the unexpected EOF happens by itself after about a minute of having the page open.</p> <p>I have an <code>onerror</code> function in JavaScript. That event doesn't fire, but <code>onclose</code> fires instead.</p> </div>

Golang WebSocket客户端,获取结果后关闭连接

<div class="post-text" itemprop="text"> <p>How I can implement this kind of scenario:</p> <p>1.I have LoginHandler which receives some user data - email and signedXml:</p> <pre><code>func LoginHandler(c *gin.Context) { var ( err error data LoginPost ) if err = c.BindJSON(&amp;data); err != nil { c.JSON(http.StatusBadRequest, gin.H{"status": "error"}) return } ... c.JSON(http.StatusOK, gin.H{"status": "ok"}) } </code></pre> <p>2.I need to send signedXml to another server via websocket</p> <p>3.Save result (success or error)</p> <p>4.Close connection</p> <p>Every HTTP request will open connection, send 1 message, get 1 result and finally close socket. I was trying with channel, but no success. Is this possible to implement my case?</p> <p><strong>UPDATE</strong></p> <pre><code>package main import ( "log" "net/url" "github.com/gorilla/mux" "github.com/gorilla/websocket" "net/http" ) func indexHandler(w http.ResponseWriter, r *http.Request) { message := r.FormValue("message") w.Write([]byte(message)) } func postHandler(w http.ResponseWriter, r *http.Request) { var ( message = r.FormValue("message") u = url.URL{Scheme: "ws", Host: "echo.websocket.org", Path: "/"} err error out []byte conn *websocket.Conn ) log.Printf("message: %s ", message) log.Printf("connecting to %s ", u.String()) conn, _, err = websocket.DefaultDialer.Dial(u.String(), nil) if err != nil { log.Fatal("dial:", err) } log.Println("write") if err = conn.WriteMessage(websocket.TextMessage, []byte(message)); err != nil { log.Fatal("write:", err) } log.Println("read") if _, out, err = conn.ReadMessage(); err != nil { log.Fatal("read:", err) } w.Write(out) log.Println("close") conn.Close() } func main() { r := mux.NewRouter() r.HandleFunc("/", indexHandler).Methods("GET") r.HandleFunc("/post", postHandler).Methods("POST") http.Handle("/", r) http.ListenAndServe(":8080", nil) } </code></pre> </div>


<div class="post-text" itemprop="text"> <p>I am new to websockets. </p> <p>In my setup I have a trivial websocket server written in Go (<a href="https://play.golang.org/p/H6ctw_tFlx" rel="nofollow noreferrer">playground</a>)</p> <p>I make a <code>WebSocket</code> object, set up its <code>onmessage</code> callback and call its <code>send</code> method to test.</p> <pre><code>var w = new WebSocket("ws://localhost:12345/echo") w.onmessage = (msg) =&gt; { console.log(msg.data) } w.onopen = () =&gt; { w.send("Hello") // this fires OK } </code></pre> <p>What I expect to happen based on the server code is to receive the "Hello" message and to keep sending "yahoo" every 1.5s to the client. What actually happens is "Hello" is sent, but none of the "yahoo"'s make it thru. It seems somewhere along the WebSocket.readystate becomes 3 (CLOSED). </p> <p>To clarify, the server receives and prints "Hello" then actually fires a "yahoo" message every 1.5s, but the connection is closed by then so the <code>onmessage</code> callback never fires.</p> <p>Am I missing or misunderstanding anything? </p> <p>EDIT: Ran across <a href="https://github.com/gorilla/websocket#gorilla-websocket-compared-with-other-packages" rel="nofollow noreferrer">comparison github.com/gorilla vs. golang.org/x/net</a>, claims golang.org/x/net websocket implementation does not support pong. This may be the confirmation of it.</p> <p>EDIT: Package golang.org/x/net/websocket closes the websocket connection when the handler ServeHTTP function returns. By default a websocket connection is tied to an instance of the handler.</p> </div>

Docker GO build返回非零代码:1

<div class="post-text" itemprop="text"> <p>Docker command to build</p> <p><code>sudo docker build -t gpst .</code></p> <pre> ubuntu@ip-172-31-9-252:~/goyo/GO/goyo.in/gpstracker$ sudo docker build -t gpst . Sending build context to Docker daemon 1.819MB Step 1/10 : FROM golang:1.8 ---&gt; a8ef0d2260ca Step 2/10 : RUN mkdir -p /go/src/goyo.in/gpstracker ---&gt; Using cache ---&gt; 70f242e31c63 Step 3/10 : WORKDIR /go/src/goyo.in/gpstracker ---&gt; Using cache ---&gt; a1609e2d1463 Step 4/10 : COPY . /go/src/goyo.in/gpstracker ---&gt; 2c90614f0f5b Step 5/10 : RUN go get github.com/codegangsta/gin ---&gt; Running in aae1a6e5d8bc ---&gt; e808aee68694 Removing intermediate container aae1a6e5d8bc Step 6/10 : RUN go-wrapper download # "go get -d -v ./..." ---&gt; Running in 427b2c574de7 + exec go get -v -d github.com/go-playground/log (download) github.com/go-playground/errors (download) github.com/tidwall/tile38 (download) package github.com/tidwall/tile38/client: cannot find package "github.com/tidwall/tile38/client" in any of: /usr/local/go/src/github.com/tidwall/tile38/client (from $GOROOT) /go/src/github.com/tidwall/tile38/client (from $GOPATH) github.com/garyburd/redigo (download) github.com/googollee/go-socket.io (download) github.com/googollee/go-engine.io (download) github.com/gorilla/websocket (download) github.com/rs/cors (download) github.com/jasonlvhit/gocron (download) github.com/NaySoftware/go-fcm (download) Fetching https://golang.org/x/net/context?go-get=1 Parsing meta tags from https://golang.org/x/net/context?go-get=1 (status code 200) get "golang.org/x/net/context": found meta tag main.metaImport{Prefix:"golang.org/x/net", VCS:"git", RepoRoot:"https://go.googlesource.com/net"} at https://golang.org/x/net/context?go-get=1 get "golang.org/x/net/context": verifying non-authoritative meta tag Fetching https://golang.org/x/net?go-get=1 Parsing meta tags from https://golang.org/x/net?go-get=1 (status code 200) golang.org/x/net (download) Fetching https://google.golang.org/grpc?go-get=1 Parsing meta tags from https://google.golang.org/grpc?go-get=1 (status code 200) get "google.golang.org/grpc": found meta tag main.metaImport{Prefix:"google.golang.org/grpc", VCS:"git", RepoRoot:"https://github.com/grpc/grpc-go"} at https://google.golang.org/grpc?go-get=1 google.golang.org/grpc (download) Fetching https://golang.org/x/text/secure/bidirule?go-get=1 Parsing meta tags from https://golang.org/x/text/secure/bidirule?go-get=1 (status code 200) get "golang.org/x/text/secure/bidirule": found meta tag main.metaImport{Prefix:"golang.org/x/text", VCS:"git", RepoRoot:"https://go.googlesource.com/text"} at https://golang.org/x/text/secure/bidirule?go-get=1 get "golang.org/x/text/secure/bidirule": verifying non-authoritative meta tag Fetching https://golang.org/x/text?go-get=1 Parsing meta tags from https://golang.org/x/text?go-get=1 (status code 200) golang.org/x/text (download) Fetching https://golang.org/x/text/unicode/bidi?go-get=1 Parsing meta tags from https://golang.org/x/text/unicode/bidi?go-get=1 (status code 200) get "golang.org/x/text/unicode/bidi": found meta tag main.metaImport{Prefix:"golang.org/x/text", VCS:"git", RepoRoot:"https://go.googlesource.com/text"} at https://golang.org/x/text/unicode/bidi?go-get=1 get "golang.org/x/text/unicode/bidi": verifying non-authoritative meta tag Fetching https://golang.org/x/text/unicode/norm?go-get=1 Parsing meta tags from https://golang.org/x/text/unicode/norm?go-get=1 (status code 200) get "golang.org/x/text/unicode/norm": found meta tag main.metaImport{Prefix:"golang.org/x/text", VCS:"git", RepoRoot:"https://go.googlesource.com/text"} at https://golang.org/x/text/unicode/norm?go-get=1 get "golang.org/x/text/unicode/norm": verifying non-authoritative meta tag github.com/golang/protobuf (download) Fetching https://google.golang.org/genproto/googleapis/rpc/status?go-get=1 Parsing meta tags from https://google.golang.org/genproto/googleapis/rpc/status?go-get=1 (status code 200) get "google.golang.org/genproto/googleapis/rpc/status": found meta tag main.metaImport{Prefix:"google.golang.org/genproto", VCS:"git", RepoRoot:"https://github.com/google/go-genproto"} at https://google.golang.org/genproto/googleapis/rpc/status?go-get=1 get "google.golang.org/genproto/googleapis/rpc/status": verifying non-authoritative meta tag Fetching https://google.golang.org/genproto?go-get=1 Parsing meta tags from https://google.golang.org/genproto?go-get=1 (status code 200) google.golang.org/genproto (download) The command '/bin/sh -c go-wrapper download # "go get -d -v ./..."' returned a non-zero code: 1 </pre> </div>

Gorilla Websocket没有收到消息

<div class="post-text" itemprop="text"> <p>I am building a gateway in Golang that communicates with Gorilla websockets.</p> <p>I am running it on Ubuntu 16.04, and testing it currently with a .NET console app.</p> <p>Using Wireshark on Windows and sniffit on Ubuntu have determined that <em>messages are being sent correctly from the Windows client and received by the Ubuntu box</em>.</p> <p>In my code, however, sometimes after a few successful messages, and sometimes after none, my gateway is failing to read the message (still sitting at <code>_, msg, errCon := conn.ReadMessage()</code>)</p> <p>An example of the output will be:</p> <blockquote> <p>2018/03/27 02:38:06 Awaiting Message ... 2018/03/27 02:38:07 Message received: main.AdminRequest{Data:"{\"SomeDataHeader\":\"SomeData\"}", Requestor:"user", Type:"JustDoSomethingRequest", Ukey:"talca"} 2018/03/27 02:38:07 {"SomeDataHeader":"SomeData"} 2018/03/27 02:38:07 Awaiting Message ...</p> </blockquote> <p>As I have previously said, it may receive a few messages like this, but, despite network traffic on both ends continuing, no more messages will be received</p> <p>I am fairly new with Golang, and working under the assumption that I am missing something.</p> <p><strike>I have trimmed out error handling and the like for the sake of brevity in the code below, but this is an example of the failing code.</strike></p> <p><strong>EDIT</strong> As requested I have added Golang full code, and C# client code below (although, as I stated, Wireshark and sniffit have determined that data is going over the wire)</p> <pre><code>package main import ( "fmt" "net/http" "github.com/gorilla/websocket" "encoding/json" "log" ) var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, CheckOrigin: func(r *http.Request) bool { return true }, } type AdminRequest struct { Data string `json:"Data"` Requestor string `json:"Requestor"` Type string `json:"Type"` Ukey string `json:"Ukey"` } func main() { http.HandleFunc("/a", func(w http.ResponseWriter, r *http.Request) { var conn, _ = upgrader.Upgrade(w, r, nil) go func(conn *websocket.Conn) { for { _, _, err := conn.ReadMessage() if err != nil { log.Println("Close: "+ err.Error()) conn.Close() return } } }(conn) go func(conn *websocket.Conn) { for { log.Println("Awaiting Message ...") _, msg, errCon := conn.ReadMessage() if errCon != nil { log.Println("Read Error:", errCon) break } log.Println("Message received: ") var r AdminRequest if err := json.Unmarshal(msg, &amp;r); err != nil { log.Println("Error: " + err.Error()); return; } fmt.Printf("%#v ", r) log.Println(r.Data); } }(conn) }) http.ListenAndServe(":3000", nil) } </code></pre> <p>C# Code:</p> <pre><code>public class Client : IDisposable { private ClientWebSocket _socket; string _address; int _port; public Client(string address) { _address = address; _socket = new ClientWebSocket(); } public async void SetupForReceivingStuffs() { while (_socket.State == WebSocketState.Open) { ArraySegment&lt;byte&gt; receivedBytes = new ArraySegment&lt;byte&gt;(new byte[1024]); WebSocketReceiveResult result = await _socket.ReceiveAsync(receivedBytes, CancellationToken.None); Console.WriteLine(Encoding.UTF8.GetString(receivedBytes.Array, 0, result.Count)); } } public async void SetupForSendingStuffs(ConcurrentQueue&lt;AdminRequest&gt; queue) { while (_socket.State == WebSocketState.Open) { AdminRequest next; while (queue.Count &gt; 0) { if (queue.TryDequeue(out next)) { await Send(next); } } await Task.Yield(); } } public async Task Connect() { while (_socket.State != WebSocketState.Open) { try { _socket = new ClientWebSocket(); await _socket.ConnectAsync(new Uri(_address), CancellationToken.None); Console.WriteLine("Socket state: " + _socket.State); } catch (Exception ex) { //Not getting hit Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } } } public Task Send&lt;TData&gt;(TData data) { string text = JsonConvert.SerializeObject(data); var encoded = Encoding.UTF8.GetBytes(text); var buffer = new ArraySegment&lt;Byte&gt;(encoded, 0, encoded.Length); return _socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); } public void Dispose() { _socket.Dispose(); } } </code></pre> <p>Called by:</p> <pre><code>class Program { static ConcurrentQueue&lt;AdminRequest&gt; _toSend; static void Main(string[] args) { _toSend = new ConcurrentQueue&lt;AdminRequest&gt;(); Client client = new Client("ws:/(myip):(myport)/a"); client.Connect().Wait(); //client.SetupForReceivingStuffs(); client.SetupForSendingStuffs(_toSend); WriteInstructions(); LoopAuto(); Console.WriteLine("Bye"); } private static void LoopAuto() { DateTime nextMessage = DateTime.Now; while (true) { if (DateTime.Now &lt; nextMessage) continue; Console.WriteLine("Next"); nextMessage = DateTime.Now.AddSeconds(2); _toSend.Enqueue(new AdminRequest { Data = "{\"SomeDataHeader\":\"SomeData\"}", Requestor = "user", Type = "JustDoSomethingRequest", Ukey = "talca" }); } } private static ConsoleKeyInfo LoopManual() { ConsoleKeyInfo info; do { info = Console.ReadKey(true); if (info.KeyChar == '1') { _toSend.Enqueue(new AdminRequest { Data = "{\"SomeDataHeader\":\"SomeData\"}", Requestor = "user", Type = "JustDoSomethingRequest", Ukey = "talca" }); } else if (info.KeyChar == 'i') { WriteInstructions(); } } while (info.KeyChar != 'x'); return info; } private static void WriteInstructions() { Console.WriteLine("1. Send New Message"); Console.WriteLine("i. Instructions (these lines)"); Console.WriteLine("x: Exit"); } } </code></pre> </div>


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

go安装iris失败, package github.com/kataras/iris: exit status 128

今天想安装个iris框架,执行命令行:go get -u -v github.com/kataras/iris 后就卡住了, 过了好久命令行提示如下: ``` PS C:\Users\dewff> go get -u github.com\kataras\iris # cd .; git clone https://github.com/kataras/iris D:\go_workspace\src\github.com\kataras\iris Cloning into 'D:\go_workspace\src\github.com\kataras\iris'... fatal: early EOF fatal: The remote end hung up unexpectedly fatal: index-pack failed error: RPC failed; curl 18 transfer closed with outstanding read data remaining package github.com/kataras/iris: exit status 128 ``` 我的git环境变量也配了,再任意目录下都可执行git --version 求大神告知啥原因????


<div class="post-text" itemprop="text"> <p>Setting up a web socket on google cloud in Golang, and import code that works fine on my local machine does not work on the cloud. </p> <p>I have:</p> <pre><code>import "github.com/influxdb/influxdb/client/v2" </code></pre> <p>and have run </p> <pre><code>go get "github.com/influxdb/influxdb/client/v2" </code></pre> <p>Upon running go run server.go I get:</p> <pre><code># command-line-arguments ./pi_server.go:47: undefined: client.NewClient ./pi_server.go:47: undefined: client.Config </code></pre> <p>Full code below, excluding const declarations and html:</p> <pre><code>package main import ( "flag" "html/template" "log" "net/http" "github.com/gorilla/websocket" "fmt" "net/url" "github.com/influxdb/influxdb/client/v2" "time" ) var addr = flag.String("addr", "localhost:8080", "http service address") var upgrader = websocket.Upgrader{} // use default options func echo(w http.ResponseWriter, r *http.Request) { //Influx init u,err := url.Parse("http://localhost:8086") checkError(err) influx_c := client.NewClient(client.Config{ URL: u, Username: username, Password: password, }) bp,err := client.NewBatchPoints(client.BatchPointsConfig{ Database: MyDB, Precision: "s", }) tags := map[string]string{"my_sensor_id": my_sensor_id} //end influx init c, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Print("upgrade:", err) return } defer c.Close() for { mt, message, err := c.ReadMessage() if err != nil { log.Println("read:", err) break } log.Printf("recv: %s", message) /* write to influx here */ fields := map[string]interface{}{ "random_int": message, "other_stuff": 69696, } pt,err := client.NewPoint("test_collection", tags, fields, time.Now()) checkError(err) bp.AddPoint(pt) influx_c.Write(bp) err = c.WriteMessage(mt, message) if err != nil { log.Println("write:", err) break } } } func home(w http.ResponseWriter, r *http.Request) { homeTemplate.Execute(w, "ws://"+r.Host+"/echo", ) } func main() { flag.Parse() log.SetFlags(0) http.HandleFunc("/echo", echo) http.HandleFunc("/", home) log.Fatal(http.ListenAndServe(*addr, nil)) } </code></pre> </div>

转到Gorilla Websocket〜在ping / pong上失败(用户断开连接)调用功能吗?

<div class="post-text" itemprop="text"> <p>I'm writing a chat program with Golang and Gorilla's Websocket toolkit.</p> <p>I'm wondering if there is a way to run a function whenever a user disconnects or a ping/pong message fails. I need this to remove them from variables and such. Is there any easy way to do this?</p> </div>


<div class="post-text" itemprop="text"> <pre><code> func handleConn(w http.ResponseWriter, r *http.Request) { ws, err := upgrader.Upgrade(w, r, nil) if err != nil { if _, ok := err.(websocket.HandshakeError); !ok { log.Println(err) } return } go writer(ws) reader(r, ws) } func main() { http.HandleFunc("/", handleConn) } </code></pre> <p>I am trying to build a high scaling websocket server using golang. Since there is lack of support in native go websocket package, i am using <a href="https://github.com/gorilla/websocket" rel="nofollow noreferrer">https://github.com/gorilla/websocket</a>. </p> <p>For every connection, a goroutine will be spawned to take care of writes to it. For scaling huge number of connections. Let's say if I have 1M concurrent connections then there should be 1M goroutines will be running on the server.</p> <p><strong>Hardware Specification:</strong></p> <p>16 GB Ram</p> <p>4 Core CPU</p> <p>2.5 GHz Intel Core i5</p> <p>will it work for large number of connections without affecting the performance?</p> </div>

如何使用Golang Gorilla / mux托管并发Websocket连接?

<div class="post-text" itemprop="text"> <p>thanks in advance for any help or advice! </p> <p>I am building a chess application, the frontend is in Reactjs and backend is a server written in Golang using Gorilla mux library. The backend is a chess engine for the human user to play against. The react frontend creates a WebSocket connection with the server in the top-level constructor. </p> <p>The app works well for a single connection. However, upon opening a second browser tab, the first browser tab's Websocket connection is lost. </p> <p>The server reports the error, </p> <pre><code>read error: websocket: close 1001 (going away) </code></pre> <p>and then,</p> <pre><code>read error: read tcp\u003e127.0.0.1:64146: use of closed network connection </code></pre> <p>I've looked at the Gorrilla/mux documentation for websockets and am reading/writing all from the same function in order to avoid concurrent reads or writes on the same connection. </p> <p>React frontend constructor is here: </p> <pre><code>class Game extends React.Component { constructor(props) { super(props); this.state = { history: [{ position: this.props.chess.fen(), move: "", }], ply: 0, selectedSq: null, engineName: "", engineAuthor: "", uciOK: false, isReady: false, engineThinking: false, playersTurn: true, playerColor: WHITE, }; this.ws = websocketConnect("ws://localhost:8081/uci"); this.ws.onmessage = (event) =&gt; { const msg = event.data this.processEngineMessage(msg) } } </code></pre> <p>It is referencing websocket.js which is here: </p> <pre><code>export function websocketConnect(url) { const ws = new WebSocket(url); ws.addEventListener('open', (event) =&gt; { ws.send('uci'); }); return ws; } </code></pre> <p>Goland Websocket package is here</p> <pre><code>package websocket import ( "net/http" "github.com/namsral/flag" log "github.com/sirupsen/logrus" "github.com/gorilla/websocket" ) type WebsocketServer struct { upgrader websocket.Upgrader addr *string conn *websocket.Conn } func NewWebsocketServer() *WebsocketServer { w := new(WebsocketServer) w.addr = flag.String("addr", "localhost:8081", "http service address") flag.Parse() w.upgrader = websocket.Upgrader{} // use default options http.HandleFunc("/uci", w.uciHandler) return w } func (w *WebsocketServer) uciHandler(rw http.ResponseWriter, r *http.Request) { var err error log.Error("upgrading to websocket connection") w.upgrader.CheckOrigin = func(r *http.Request) bool { return true } w.conn, err = w.upgrader.Upgrade(rw, r, nil) if err != nil { log.Print("upgrade:", err) return } go w.UCI(rw, r) } func (w *WebsocketServer) Start() { log.Info("starting websocket server") http.ListenAndServe(*w.addr, nil) } func (w *WebsocketServer) CloseConnection() { w.conn.Close() } func (w *WebsocketServer) StartReader(channel chan string) { for { _, message, err := w.conn.ReadMessage() if err != nil { log.Println("read error:", err) break } log.Printf("recv: %s", message) channel &lt;- string(message) } } func (w *WebsocketServer) Write(msg string) { err := w.conn.WriteMessage(websocket.TextMessage, []byte(msg)) if err != nil { log.Println("write:", err) } } </code></pre> <p>Full code here: server: <a href="https://github.com/tonyOreglia/glee" rel="nofollow noreferrer">https://github.com/tonyOreglia/glee</a> frontend: <a href="https://github.com/tonyOreglia/chess-board-react" rel="nofollow noreferrer">https://github.com/tonyOreglia/chess-board-react</a></p> <p>I am hoping to be able to support multiple concurrent users using the website. It is currently hosted on DigitalOcean.</p> </div>

MySQL 8.0.19安装教程(windows 64位)

话不多说直接开干 目录 1-先去官网下载点击的MySQL的下载​ 2-配置初始化的my.ini文件的文件 3-初始化MySQL 4-安装MySQL服务 + 启动MySQL 服务 5-连接MySQL + 修改密码 先去官网下载点击的MySQL的下载 下载完成后解压 解压完是这个样子 配置初始化的my.ini文件的文件 ...



Vue.js 2.0之全家桶系列视频课程

基于新的Vue.js 2.3版本, 目前新全的Vue.js教学视频,让你少走弯路,直达技术前沿! 1. 包含Vue.js全家桶(vue.js、vue-router、axios、vuex、vue-cli、webpack、ElementUI等) 2. 采用笔记+代码案例的形式讲解,通俗易懂






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




时钟功能 还有闹钟功能,温湿度功能,整点报时功能 你值得拥有

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

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

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



获取讲师答疑方式: 在付费视频第一节(触摸命令_ALL)片头有二维码及加群流程介绍 限时福利 原价99元,今日仅需39元!购课添加小助手(微信号:itxy41)按提示还可领取价值800元的编程大礼包! 讲师介绍: 苏奕嘉&nbsp;前阿里UC项目工程师 脚本开发平台官方认证满级(六级)开发者。 我将如何教会你通过【定制脚本】赚到你人生的第一桶金? 零基础程序定制脚本开发课程,是完全针对零脚本开发经验的小白而设计,课程内容共分为3大阶段: ①前期将带你掌握Q开发语言和界面交互开发能力; ②中期通过实战来制作有具体需求的定制脚本; ③后期将解锁脚本的更高阶玩法,打通任督二脉; ④应用定制脚本合法赚取额外收入的完整经验分享,带你通过程序定制脚本开发这项副业,赚取到你的第一桶金!


原价169,限时立减100元! 系统掌握Python核心语法16点,轻松应对工作中80%以上的Python使用场景! 69元=72讲+源码+社群答疑+讲师社群分享会&nbsp; 【哪些人适合学习这门课程?】 1)大学生,平时只学习了Python理论,并未接触Python实战问题; 2)对Python实用技能掌握薄弱的人,自动化、爬虫、数据分析能让你快速提高工作效率; 3)想学习新技术,如:人工智能、机器学习、深度学习等,这门课程是你的必修课程; 4)想修炼更好的编程内功,优秀的工程师肯定不能只会一门语言,Python语言功能强大、使用高效、简单易学。 【超实用技能】 从零开始 自动生成工作周报 职场升级 豆瓣电影数据爬取 实用案例 奥运冠军数据分析 自动化办公:通过Python自动化分析Excel数据并自动操作Word文档,最终获得一份基于Excel表格的数据分析报告。 豆瓣电影爬虫:通过Python自动爬取豆瓣电影信息并将电影图片保存到本地。 奥运会数据分析实战 简介:通过Python分析120年间奥运会的数据,从不同角度入手分析,从而得出一些有趣的结论。 【超人气老师】 二两 中国人工智能协会高级会员 生成对抗神经网络研究者 《深入浅出生成对抗网络:原理剖析与TensorFlow实现》一书作者 阿里云大学云学院导师 前大型游戏公司后端工程师 【超丰富实用案例】 0)图片背景去除案例 1)自动生成工作周报案例 2)豆瓣电影数据爬取案例 3)奥运会数据分析案例 4)自动处理邮件案例 5)github信息爬取/更新提醒案例 6)B站百大UP信息爬取与分析案例 7)构建自己的论文网站案例


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


&nbsp; &nbsp; &nbsp; &nbsp; 本课程为Python数据挖掘方向的入门课程,课程主要以真实数据为基础,详细介绍数据挖掘入门的流程和使用Python实现pandas与numpy在数据挖掘方向的运用,并深入学习如何运用scikit-learn调用常用的数据挖掘算法解决数据挖掘问题,为进一步深入学习数据挖掘打下扎实的基础。


本课程从初学者角度出发,提供了C#从入门到成为程序开发高手所需要掌握的各方面知识和技术。 【课程特点】 1 由浅入深,编排合理; 2 视频讲解,精彩详尽; 3 丰富实例,轻松易学; 4 每章总结配有难点解析文档。 15大章节,228课时,1756分钟与你一同进步!






想学好JAVA必须要报两万的培训班吗? Java大神勿入 如果你: 零基础想学JAVA却不知道从何入手 看了一堆书和视频却还是连JAVA的环境都搭建不起来 囊中羞涩面对两万起的JAVA培训班不忍直视 在职没有每天大块的时间专门学习JAVA 那么恭喜你找到组织了,在这里有: 1. 一群志同道合立志学好JAVA的同学一起学习讨论JAVA 2. 灵活机动的学习时间完成特定学习任务+每日编程实战练习 3. 热心助人的助教和讲师及时帮你解决问题,不按时完成作业小心助教老师的家访哦 上一张图看看前辈的感悟: &nbsp; &nbsp; 大家一定迫不及待想知道什么是极简JAVA学习营了吧,下面就来给大家说道说道: 什么是极简JAVA学习营? 1. 针对Java小白或者初级Java学习者; 2. 利用9天时间,每天1个小时时间; 3.通过 每日作业 / 组队PK / 助教答疑 / 实战编程 / 项目答辩 / 社群讨论 / 趣味知识抢答等方式让学员爱上学习编程 , 最终实现能独立开发一个基于控制台的‘库存管理系统’ 的学习模式 极简JAVA学习营是怎么学习的? &nbsp; 如何报名? 只要购买了极简JAVA一:JAVA入门就算报名成功! &nbsp;本期为第四期极简JAVA学习营,我们来看看往期学员的学习状态: 作业看这里~ &nbsp; 助教的作业报告是不是很专业 不交作业打屁屁 助教答疑是不是很用心 &nbsp; 有奖抢答大家玩的很嗨啊 &nbsp; &nbsp; 项目答辩终于开始啦 &nbsp; 优秀者的获奖感言 &nbsp; 这是答辩项目的效果 &nbsp; &nbsp; 这么细致的服务,这么好的氛围,这样的学习效果,需要多少钱呢? 不要1999,不要199,不要99,只要9.9 是的你没听错,只要9.9以上所有就都属于你了 如果你: 1、&nbsp;想学JAVA没有基础 2、&nbsp;想学JAVA没有整块的时间 3、&nbsp;想学JAVA没有足够的预算 还等什么?赶紧报名吧,抓紧抢位,本期只招300人,错过只有等时间待定的下一期了 &nbsp; 报名请加小助手微信:eduxy-1 &nbsp; &nbsp;


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


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


机器学习实战系列套餐以实战为出发点,帮助同学们快速掌握机器学习领域必备经典算法原理并结合Python工具包进行实战应用。建议学习顺序:1.Python必备工具包:掌握实战工具 2.机器学习算法与实战应用:数学原理与应用方法都是必备技能 3.数据挖掘实战:通过真实数据集进行项目实战。按照下列课程顺序学习即可! 课程风格通俗易懂,用最接地气的方式带领大家轻松进军机器学习!提供所有课程代码,PPT与实战数据,有任何问题欢迎随时与我讨论。


发现网上很多Java面试题都没有答案,所以花了很长时间搜集整理出来了这套Java面试题大全,希望对大家有帮助哈~ 本套Java面试题大全,全的不能再全,哈哈~ 一、Java 基础 1. JDK 和 JRE 有什么区别? JDK:Java Development Kit 的简称,java 开发工具包,提供了 java 的开发环境和运行环境。 JRE:Java Runtime Environ...


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


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


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


本文的面试题如下: Redis 持久化机制 缓存雪崩、缓存穿透、缓存预热、缓存更新、缓存降级等问题 热点数据和冷数据是什么 Memcache与Redis的区别都有哪些? 单线程的redis为什么这么快 redis的数据类型,以及每种数据类型的使用场景,Redis 内部结构 redis的过期策略以及内存淘汰机制【~】 Redis 为什么是单线程的,优点 如何解决redis的并发竞争key问题 Red...



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

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


YOLOv3是一种基于深度学习的端到端实时目标检测方法,以速度快见长。本课程将手把手地教大家使用labelImg标注和使用YOLOv3训练自己的数据集。课程分为三个小项目:足球目标检测(单目标检测)、梅西目标检测(单目标检测)、足球和梅西同时目标检测(两目标检测)。 本课程的YOLOv3使用Darknet,在Ubuntu系统上做项目演示。包括:安装Darknet、给自己的数据集打标签、整理自己的数据集、修改配置文件、训练自己的数据集、测试训练出的网络模型、性能统计(mAP计算和画出PR曲线)和先验框聚类。 Darknet是使用C语言实现的轻型开源深度学习框架,依赖少,可移植性好,值得深入探究。 除本课程《YOLOv3目标检测实战:训练自己的数据集》外,本人推出了有关YOLOv3目标检测的系列课程,请持续关注该系列的其它课程视频,包括: 《YOLOv3目标检测实战:交通标志识别》 《YOLOv3目标检测:原理与源码解析》 《YOLOv3目标检测:网络模型改进方法》 敬请关注并选择学习!



相关热词 c#树形选择 c#中类图的使用方法 c# 传参 调用exe c# 怎么定义方法 c# 修改本地时间 c#前台怎么读取资源文件 c# xml转list c#实现框选截图 m*m乘法表c# c# 乘法99表