带有Web代理的Golang Gorilla Websocket

I'm working on a POC using Gorilla/Websocket to communicate, through a Web Proxy, with the Websocket Check Website "echo.websocket.org".

I'm using the free online Proxy "hide.me/en/" for testing.

When I simply try to communicate with "echo.websocket.org" (Server side), my client-site Websocket POC reach the response.

But when i try to add the Proxy gesture, everything goes wrong :(

Here is a sample of my 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 ==> with this default dialer, it works !

    c, _, err := dialer.Dial(uWS.String(), nil) // ==> 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 := <-ticker.C:
            err := c.WriteMessage(websocket.TextMessage, []byte(t.String()))
            if err != nil {
                log.Println("write:", err)
                return
            }
        case <-interrupt:
            log.Println("interrupt")
            err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
            if err != nil {
                log.Println("write close:", err)
                return
            }
                select {
                case <-done:
                case <-time.After(time.Second):
                }
            c.Close()
            return
        }
    }
}

I'm a very beginner in Go so don't hesitate to correct me if my code un not clear and clean.

Thanks for your help !

donglanying3855
donglanying3855 您建议的测试也给出400个“错误请求”。但是当我拿出代理服务器时,它变成“200OK”。因此,也许我没有以应有的方式使用Web代理...您是否对其他可以响应我的需求的在线代理有任何建议?再次感谢你的帮助
4 年多之前 回复
dosf40815
dosf40815 错误请求响应可能表明hide.me/en/proxy不支持CONNECT。
4 年多之前 回复
duankuiyu4618
duankuiyu4618 我建议您在不升级websocket的情况下通过代理测试HTTP请求。创建具有代理URL的客户端:c:=http.Client{传输:&http.Transport{代理:http.ProxyURL(uProxy)}},确认c.Get(“http://stackoverflow.com/)有效。如果可行,请尝试了解websocket的情况。
4 年多之前 回复
dongyuxiao6295
dongyuxiao6295 这是用于匿名导航的在线代理解决方案。我认为这是测试Websocket客户端的良好外部代理解决方案。您能否解释一下golang中“纯HTTP请求”的确切建议?谢谢
4 年多之前 回复
douyan2970
douyan2970 hide.me/en/proxy是代理服务器吗?我建议使用简单的HTTP请求对其进行测试。
4 年多之前 回复
dongwei3336
dongwei3336 您好,这是一个“400错误请求”
4 年多之前 回复
donglu9445
donglu9445 从失败的函数返回的错误是什么?
4 年多之前 回复

1个回答



代码正确。 服务器 https://hide.me 不是代理服务器。</ p>
</ div>

展开原文

原文

The code is correct. The server https://hide.me is not a proxy server.

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

使用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与golang.org/x/net/websocket的比较

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

一分钟后,Gorilla WebSocket断开连接

<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 http://127.0.0.1:1234; } } </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>

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

如何确保Golang大猩猩WebSocket包中的并发

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

使用Golang扩展WebSocket连接

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

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>

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 WebSocket数据不正确

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

如何从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>

golang websocket当浏览器意外关闭时如何通知

<div class="post-text" itemprop="text"> <p>I am writing a websocket service in golang. The program use gollira websocket to accept ws request, and in each request handler, it listen to rabbitmq queue for messages.</p> <p>The problem is, when i close browser window, the handler thread is still running, i guess there is an mechanism to be notified when connection disconnected.</p> <p>I try to listen to channel request.Context().Done(), when i doesn't work.</p> <pre><code>package main import ( "fmt" "log" "net/http" "github.com/gorilla/websocket" "github.com/streadway/amqp" ) var ( addr = "localhost:9999" upgrader = websocket.Upgrader{ CheckOrigin: func(r *http.Request) bool { return true }, } ) var conn *amqp.Connection func watch(w http.ResponseWriter, r *http.Request) { ns := r.URL.Query().Get("ns") if ns == "" { return } c, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Print("upgrade:", err) return } defer c.Close() ch, err := conn.Channel() failOnError(err, "Failed to open a channel") defer ch.Close() err = ch.ExchangeDeclare( "notify", // name "fanout", // type true, // durable false, // auto-deleted false, // internal false, // no-wait nil, // arguments ) failOnError(err, "Failed to declare an exchange") q, err := ch.QueueDeclare( "", // name false, // durable false, // delete when usused true, // exclusive false, // no-wait nil, // arguments ) failOnError(err, "Failed to declare a queue") err = ch.QueueBind( q.Name, // queue name ns, // routing key "dsm_tasks_notify", // exchange false, nil) failOnError(err, "Failed to bind a queue") msgs, err := ch.Consume( q.Name, // queue "", // consumer true, // auto-ack false, // exclusive false, // no-local false, // no-wait nil, // args ) failOnError(err, "Failed to register a consumer") for { select { case d := &lt;-msgs: err = c.WriteMessage(websocket.TextMessage, d.Body) if err != nil { log.Println("write:", err) break } case &lt;-r.Context().Done(): log.Println("Disconnect") return } } } func failOnError(err error, msg string) { if err != nil { log.Fatalf("%s: %s", msg, err) panic(fmt.Sprintf("%s: %s", msg, err)) } } func main() { var err error conn, err = amqp.Dial("amqp://guest:guest@localhost:5672/") failOnError(err, "Failed to connect to RabbitMQ") defer conn.Close() http.HandleFunc("/watch", watch) log.Fatal(http.ListenAndServe(addr, nil)) } </code></pre> </div>

Gorilla Websocket-读取错误:在失败的Websocket连接上重复读取

<div class="post-text" itemprop="text"> <p>Using the gorilla websocket api for go, how do i know if a client is still connected?</p> <p>What Im trying with now is: </p> <pre><code>func Listen(ws *websocket.Conn) { connTimeout := 3 timeLastSent := time.Now().Second() for ((timeLastSent + connTimeout) % 60) != time.Now().Second() { msg := Message{} err := ws.ReadJSON(&amp;msg) if err == websocket.ErrCloseSent { break } else if err != nil { continue } //Message recived EventMessage &lt;- msg timeLastSent = time.Now().Second() } //Connection timed out. return } </code></pre> <p>But this results in the error <code>repeated read on failed websocket connection</code>. </p> <p>Ive been looking into using <code>ws.SetReadDeadline(t)</code>, but Ive no idea of either how to use it nor if its even the thing Im looking for.</p> <p>How should i go about this? </p> </div>

Golang WebSocket处理程序

<div class="post-text" itemprop="text"> <p>I've started learning Golang after writing in Node.js for a long time and I'm a bit curious as to how am I to implement a handler - I've opted to use Gorilla Websocket since I understood it's the most reliable package out there.</p> <p>In socket.io for example you have the simple socket.on function that allows me to call a function based on the "name" parameter passed in JSON.</p> <p>Gorilla websocket doesn't implement such a thing, so my question is am I to sort of implement the logic behind socket.io in order to achieve what I want ?</p> <p>As in do a certain procedure based on the value transferred in the websocket ?</p> <p>If so - I need to implement it both client (I'm using AngularJS on the front-end) and server side separately by my own - make a switch case statement based on a value I get in JSON both in AngularJS for the front-end and in Go for the back-end, and also - is that the most efficient way ?</p> <p>Thanks !</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>

Golang超时或提早返回

<div class="post-text" itemprop="text"> <p>I'm attempting to build a realtime multiplayer game server in Golang using websockets as a learning project, and I'm having difficulty understanding how exactly I'm supposed to implement this concept:</p> <p>All of the users in a game room are given a duration, <code>MAX_TIMEOUT</code> to respond to a prompt provided. Responses are submitted via websocket connections. If all of the users respond before <code>MAX_TIMEOUT</code>, then <code>Action A</code> should happen, using the responses. If <code>MAX_TIMEOUT</code> elapses before all of the prompts are submitted, then <code>Action B</code> should happen, using the responses available.</p> <p>Coming from Node.JS, I could see myself implementing this with Promises, but in Golang, I'm rather lost.</p> <p>Any advice?</p> </div>

Golang WebSocket应用程序中的身份验证

<div class="post-text" itemprop="text"> <p>I am trying to implement user authentication in an application that primarily uses WebSockets, but I am unsure how to begin.</p> <p>I am using the Gorilla mux and websocket packages.</p> <p>I have thought about using the method described <a href="https://github.com/matryer/goblueprints/tree/master/chapter3/chat" rel="nofollow">here</a> (files main.go and auth.go), but does this approach secure against authenticated users somehow hijacking each others sockets like described in <a href="https://auth0.com/blog/2014/01/15/auth-with-socket-io/" rel="nofollow">this article</a>?</p> <p>Can someone suggest a good method or package(s) 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>

Golang-扩展websocket客户端以实现与不同服务器的多个连接

<div class="post-text" itemprop="text"> <p>I have a websocket client. In reality, it is far more complex than the basic code shown below. I now need to scale this client code to open connections to multiple servers. Ultimately, the tasks that need to be performed when a message is received from the servers is identical. What would be the best approach to handle this? As I said above the actual code performed when receiving the message is far more complex than shown in the example.</p> <pre><code>package main import ( "flag" "log" "net/url" "os" "os/signal" "time" "github.com/gorilla/websocket" ) var addr = flag.String("addr", "localhost:1234", "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: "ws", Host: *addr, Path: "/echo"} u := url.URL{Scheme: "ws", Host: *addr, Path: "/"} 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) } }() ticker := time.NewTicker(time.Second) defer ticker.Stop() for { select { case &lt;-done: return 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") // 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> </div>

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

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

Vue + Spring Boot 项目实战(十九):Web 项目优化解决方案

快来一起探索如何打脸我们的破项目,兄弟姐妹们把害怕打在公屏上!

你连存活到JDK8中著名的Bug都不知道,我怎么敢给你加薪

CopyOnWriteArrayList.java和ArrayList.java,这2个类的构造函数,注释中有一句话 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public ArrayList(Collection&lt;? ...

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

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

CSDN:因博主近期注重写专栏文章(已超过150篇),订阅博主专栏人数在突增,近期很有可能提高专栏价格(已订阅的不受影响),提前声明,敬请理解!

CSDN:因博主近期注重写专栏文章(已超过150篇),订阅博主专栏人数在突增,近期很有可能提高专栏价格(已订阅的不受影响),提前声明,敬请理解! 目录 博客声明 大数据了解博主粉丝 博主的粉丝群体画像 粉丝群体性别比例、年龄分布 粉丝群体学历分布、职业分布、行业分布 国内、国外粉丝群体地域分布 博主的近期访问每日增量、粉丝每日增量 博客声明 因近期博主写专栏的文章越来越多,也越来越精细,逐步优化文章。因此,最近一段时间,订阅博主专栏的人数增长也非常快,并且专栏价

一个HashMap跟面试官扯了半个小时

一个HashMap能跟面试官扯上半个小时 关注 安琪拉的博客 1.回复面试领取面试资料 2.回复书籍领取技术电子书 3.回复交流领取技术电子书 前言 HashMap应该算是Java后端工程师面试的必问题,因为其中的知识点太多,很适合用来考察面试者的Java基础。 开场 面试官: 你先自我介绍一下吧! 安琪拉: 我是安琪拉,草丛三婊之一,最强中单(钟馗不服)!哦,不对,串场了,我是**,目...

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

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

记录下入职中软一个月(外包华为)

我在年前从上一家公司离职,没想到过年期间疫情爆发,我也被困在家里,在家呆着的日子让人很焦躁,于是我疯狂的投简历,看面试题,希望可以进大公司去看看。 我也有幸面试了我觉得还挺大的公司的(虽然不是bat之类的大厂,但是作为一名二本计算机专业刚毕业的大学生bat那些大厂我连投简历的勇气都没有),最后选择了中软,我知道这是一家外包公司,待遇各方面甚至不如我的上一家公司,但是对我而言这可是外包华为,能...

面试:第十六章:Java中级开发

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

培训班出来的人后来都怎么样了?(二)

接着上回说,培训班学习生涯结束了。后面每天就是无休止的背面试题,不是没有头脑的背,培训公司还是有方法的,现在回想当时背的面试题好像都用上了,也被问到了。回头找找面试题,当时都是打印下来天天看,天天背。 不理解呢也要背,面试造飞机,上班拧螺丝。班里的同学开始四处投简历面试了,很快就有面试成功的,刚开始一个,然后越来越多。不知道是什么原因,尝到胜利果实的童鞋,不满足于自己通过的公司,嫌薪水要少了,选择...

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

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

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

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

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

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

工作八年,月薪60K,裸辞两个月,投简历投到怀疑人生!

近日,有网友在某职场社交平台吐槽,自己裸辞两个月了,但是找工作却让自己的心态都要崩溃了,全部无果,不是已查看无回音,就是已查看不符合。 “工作八年,两年一跳,裸辞两个月了,之前月薪60K,最近找工作找的心态崩了!所有招聘工具都用了,全部无果,不是已查看无回音,就是已查看不符合。进头条,滴滴之类的大厂很难吗???!!!投简历投的开始怀疑人生了!希望 可以收到大厂offer” 先来看看网...

大牛都会用的IDEA调试技巧!!!

导读 前天面试了一个985高校的实习生,问了他平时用什么开发工具,他想也没想的说IDEA,于是我抛砖引玉的问了一下IDEA的调试用过吧,你说说怎么设置断点...

都前后端分离了,咱就别做页面跳转了!统统 JSON 交互

文章目录1. 无状态登录1.1 什么是有状态1.2 什么是无状态1.3 如何实现无状态1.4 各自优缺点2. 登录交互2.1 前后端分离的数据交互2.2 登录成功2.3 登录失败3. 未认证处理方案4. 注销登录 这是本系列的第四篇,有小伙伴找不到之前文章,松哥给大家列一个索引出来: 挖一个大坑,Spring Security 开搞! 松哥手把手带你入门 Spring Security,别再问密...

97年世界黑客编程大赛冠军作品(大小仅为16KB),惊艳世界的编程巨作

这是世界编程大赛第一名作品(97年Mekka ’97 4K Intro比赛)汇编语言所写。 整个文件只有4095个字节, 大小仅仅为16KB! 不仅实现了3D动画的效果!还有一段震撼人心的背景音乐!!! 内容无法以言语形容,实在太强大! 下面是代码,具体操作看最后! @echo off more +1 %~s0|debug e100 33 f6 bf 0 20 b5 10 f3 a5...

程序员是做全栈工程师好?还是专注一个领域好?

昨天,有位大一的同学私信我,说他要做全栈工程师。 我一听,这不害了孩子么,必须制止啊。 谁知,讲到最后,更确定了他做全栈程序员的梦想。 但凡做全栈工程师的,要么很惨,要么很牛! 但凡很牛的,绝不是一开始就是做全栈的! 全栈工程师听起来好听,但绝没有你想象的那么简单。 今天听我来给你唠,记得帮我点赞哦。 一、全栈工程师的职责 如果你学习编程的目的只是玩玩,那随意,想怎么学怎么学。...

不要再到处使用 === 了

我们知道现在的开发人员都使用 === 来代替 ==,为什么呢?我在网上看到的大多数教程都认为,要预测 JavaScript 强制转换是如何工作这太复杂了,因此建议总是使用===。这些都...

什么是a站、b站、c站、d站、e站、f站、g站、h站、i站、j站、k站、l站、m站、n站?00后的世界我不懂!

A站 AcFun弹幕视频网,简称“A站”,成立于2007年6月,取意于Anime Comic Fun,是中国大陆第一家弹幕视频网站。A站以视频为载体,逐步发展出基于原生内容二次创作的完整生态,拥有高质量互动弹幕,是中国弹幕文化的发源地;拥有大量超粘性的用户群体,产生输出了金坷垃、鬼畜全明星、我的滑板鞋、小苹果等大量网络流行文化,也是中国二次元文化的发源地。 B站 全称“哔哩哔哩(bilibili...

十个摸鱼,哦,不对,是炫酷(可以玩一整天)的网站!!!

文章目录前言正文**1、Kaspersky Cyberthreat real-time map****2、Finding Home****3、Silk – Interactive Generative Art****4、Liquid Particles 3D****5、WINDOWS93****6、Staggering Beauty****7、Ostagram图片生成器网址****8、全历史网址*...

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

用了这个 IDE 插件,5分钟解决前后端联调!

点击上方蓝色“程序猿DD”,选择“设为星标”回复“资源”获取独家整理的学习资料!作者 |李海庆我是一个 Web 开发前端工程师,受到疫情影响,今天是我在家办公的第78天。开发了两周,...

大厂的 404 页面都长啥样?最后一个笑了...

每天浏览各大网站,难免会碰到404页面啊。你注意过404页面么?猿妹搜罗来了下面这些知名网站的404页面,以供大家欣赏,看看哪个网站更有创意: 正在上传…重新上传取消 腾讯 正在上传…重新上传取消 网易 淘宝 百度 新浪微博 正在上传…重新上传取消 新浪 京东 优酷 腾讯视频 搜...

自从喜欢上了B站这12个UP主,我越来越觉得自己是个废柴了!

不怕告诉你,我自从喜欢上了这12个UP主,哔哩哔哩成为了我手机上最耗电的软件,几乎每天都会看,可是吧,看的越多,我就越觉得自己是个废柴,唉,老天不公啊,不信你看看…… 间接性踌躇满志,持续性混吃等死,都是因为你们……但是,自己的学习力在慢慢变强,这是不容忽视的,推荐给你们! 都说B站是个宝,可是有人不会挖啊,没事,今天咱挖好的送你一箩筐,首先啊,我在B站上最喜欢看这个家伙的视频了,为啥 ,咱撇...

代码注释如此沙雕,会玩还是你们程序员!

某站后端代码被“开源”,同时刷遍全网的,还有代码里的那些神注释。 我们这才知道,原来程序员个个都是段子手;这么多年来,我们也走过了他们的无数套路… 首先,产品经理,是永远永远吐槽不完的!网友的评论也非常扎心,说看这些代码就像在阅读程序员的日记,每一页都写满了对产品经理的恨。 然后,也要发出直击灵魂的质问:你是尊贵的付费大会员吗? 这不禁让人想起之前某音乐app的穷逼Vip,果然,穷逼在哪里都是...

Java14 新特性解读

Java14 已于 2020 年 3 月 17 号发布,官方特性解读在这里:https://openjdk.java.net/projects/jdk/14/以下是个人对于特性的中文式...

前端还能这么玩?(女朋友生日,用前端写了一个好玩的送给了她,高兴坏了)

前端还能这么玩?(女朋友生日,用前端写了一个好玩的送给了她,高兴坏了)

爬虫(101)爬点重口味的

小弟最近在学校无聊的很哪,浏览网页突然看到一张图片,都快流鼻血。。。然后小弟冥思苦想,得干一点有趣的事情python 爬虫库安装https://s.taobao.com/api?_ks...

工作两年简历写成这样,谁要你呀!

作者:小傅哥 博客:https://bugstack.cn 沉淀、分享、成长,让自己和他人都能有所收获! 一、前言 最近有伙伴问小傅哥,我的简历怎么投递了都没有反应,心里慌的很呀。 工作两年了目前的公司没有什么大项目,整天的维护别人的代码,有坑也不让重构,都烦死了。荒废我一身技能无处施展,投递的简历也没人看。我是不动物园里的猩猩,狒狒了! 我要加班,我要996,我要疯狂编码,求给我个机会… ...

相关热词 c# 开发接口 c# 中方法上面的限制 c# java 时间戳 c#单元测试入门 c# 数组转化成文本 c#实体类主外键关系设置 c# 子函数 局部 c#窗口位置设置 c# list 查询 c# 事件 执行顺序
立即提问
相关内容推荐