Gorilla Websocket没有收到消息

I am building a gateway in Golang that communicates with Gorilla websockets.

I am running it on Ubuntu 16.04, and testing it currently with a .NET console app.

Using Wireshark on Windows and sniffit on Ubuntu have determined that messages are being sent correctly from the Windows client and received by the Ubuntu box.

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 _, msg, errCon := conn.ReadMessage())

An example of the output will be:

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

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

I am fairly new with Golang, and working under the assumption that I am missing something.

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.

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

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, &r); err != nil {

                    log.Println("Error: " + err.Error());
                    return;
                }

                fmt.Printf("%#v
", r)
                log.Println(r.Data);
            }           
        }(conn)

    })

    http.ListenAndServe(":3000", nil)
}

C# 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<byte> receivedBytes = new ArraySegment<byte>(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<AdminRequest> queue)
        {
            while (_socket.State == WebSocketState.Open)
            {
                AdminRequest next;

                while (queue.Count > 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<TData>(TData data)
        {
            string text = JsonConvert.SerializeObject(data);

            var encoded = Encoding.UTF8.GetBytes(text);
            var buffer = new ArraySegment<Byte>(encoded, 0, encoded.Length);

            return _socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
        }


        public void Dispose()
        {
            _socket.Dispose();
        }
    }

Called by:

class Program
{
    static ConcurrentQueue<AdminRequest> _toSend;

    static void Main(string[] args)
    {
        _toSend = new ConcurrentQueue<AdminRequest>();

        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 < 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");
    }
}
douxiong0668
douxiong0668 我在原始代码中进行了检查(请检查上面的编辑),但是为了简洁起见,最初对其进行了编辑。我现在变得更加冗长。
2 年多之前 回复
douqiao5543
douqiao5543 我添加了来自服务器端(golang)和客户端(.NET)的所有代码
2 年多之前 回复
duan010167787
duan010167787 您可以尝试err:=conn.WriteMessage(1,[]byte(“testmessage”)),然后在发送至客户端时检查错误
2 年多之前 回复
drpsrvu85668
drpsrvu85668 显示实际代码。到目前为止显示的代码看起来还可以。哪个客户端用于向服务器发送消息?
2 年多之前 回复

1个回答

The application runs two goroutines that read messages in a loop. The first does nothing with the received message. The second parses and logs the message. You do not see any output because the first goroutine is receiving the messages.

The first goroutine does not seem to serve any purpose. Delete the first goroutine to fix the problem.

Deleting the first goroutine also fixes a data race. Concurrent reads on a websocket connection are not supported. The race detector will report this issue.

Here's the updated code with other fixes and improvements. The net/http server calls handlers a per-connection goroutine. Use tha goroutine instead of starting yet another goroutine. Use the websocket package's JSON helper method.

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 wsHandler(w http.ResponseWriter, r *http.Request) {
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Println(err)
        return
    }
    defer conn.Close()
    for {
        var r AdminRequest
        if err := conn.ReadJSON(&r); err != nil {
            log.Println(err)
            break
        }
        fmt.Printf("%#v
", r)
        log.Println(r.Data);
    }           
}

func main() {
    http.HandleFunc("/a", wsHandler)
    http.ListenAndServe(":3000", nil)
}
dongzu3511
dongzu3511 为了回答第一个goroutine的问题,它是在客户端请求连接/退出连接时关闭连接,但是我可以通过检查读取的JSON上的err来轻松处理该连接。
2 年多之前 回复
douzhuoxia0587
douzhuoxia0587 非常感谢,我正在拔头发。 我会对其进行测试,然后将您标记为答案。 一切都说得通,但对于golang还是一个新手,对我来说仍然不是那么直观
2 年多之前 回复
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>

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

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

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

将golang与大猩猩websocket库一起使用,为什么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>

向两个客户端发送websocket消息

<div class="post-text" itemprop="text"> <p>I started a personal project from gorilla chat example. Every time a client calls "register" I check if it has an opponent. Suppose clients are game players. What I am trying to do is to couple clients two per two.</p> <p>Clients are:</p> <pre><code>type Client struct { hub *Hub opponent *Client conn *websocket.Conn send chan []byte } </code></pre> <p>So when I client call register, if exists one client with opponent nil, I tie two clients with</p> <pre><code>c.opponent = client client.opponent = c </code></pre> <p>And then, I send together a message:</p> <pre><code>c.conn.WriteMessage(websocket.TextMessage, dat) client.conn.WriteMessage(websocket.TextMessage, dat) </code></pre> <p>but no one receive the message. How can I send a message to just two clients?</p> <pre><code>package main import ( "github.com/gorilla/websocket" "log" ) func newHub() *Hub { return &amp;Hub{ broadcast: make(chan []byte), register: make(chan *Client), unregister: make(chan *Client), clients: make(map[*Client]bool), } } func (h *Hub) run() { for { select { // register new client case client := &lt;-h.register: log.Println("register") h.clients[client] = true for c := range h.clients { if c != client { if c.opponent == nil { c.opponent = client client.opponent = c dat := []byte(`{"foo":"bar"}`) c.conn.WriteMessage(websocket.TextMessage, dat) client.conn.WriteMessage(websocket.TextMessage, dat) } } } case client := &lt;-h.unregister: log.Println("unregister") if _, ok := h.clients[client]; ok { delete(h.clients, client) close(client.send) } case message := &lt;-h.broadcast: for client := range h.clients { select { case client.send &lt;- message: default: close(client.send) delete(h.clients, client) } } } } } </code></pre> </div>

转到Nginx Websocket“在收到握手响应之前,连接已关闭”

<div class="post-text" itemprop="text"> <p>I have a Go web server running on my localhost. I'm using Nginx as a reverse proxy to change the protocol to <code>ws</code> when a certain route is accessed on my server.</p> <p>I keep getting this error message in my browser - <code>(index):13 WebSocket connection to 'ws://127.0.0.1:8080/ws' failed: Connection closed before receiving a handshake response</code></p> <p>In addition, the Go server keeps printing this error - <code>read tcp [::1]:8080-&gt;[::1]:59967: read: connection reset by peer</code></p> <p>I've tried a number of combinations in my nginx.conf file. I can't seem to get any of them to work.</p> <p>Go:</p> <pre><code>package main import ( "fmt" "log" "net/http" "github.com/gorilla/websocket" ) func reader(conn *websocket.Conn) { for { messageType, p, err := conn.ReadMessage() if err != nil { log.Println(err) return } fmt.Println(string(p)) if err := conn.WriteMessage(messageType, p); err != nil { log.Println(err) return } } } func homePage(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Home Page") } func wsEndpoint(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World") ws, err := websocket.Upgrade(w, r, nil, 1024, 1024) if err != nil { http.Error(w, "Could not open websocket connection", http.StatusBadRequest) log.Println(err) return } log.Println("Client Connected") err = ws.WriteMessage(1, []byte("Hi Client!")) if err != nil { log.Println("Error") log.Println(err) return } reader(ws) } func setupRoutes() { http.HandleFunc("/", homePage) http.HandleFunc("/ws", wsEndpoint) } func main() { fmt.Println("Hello World") setupRoutes() log.Fatal(http.ListenAndServe(":8080", nil)) } </code></pre> <p>index.html</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8" /&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt; &lt;meta http-equiv="X-UA-Compatible" content="ie=edge" /&gt; &lt;title&gt;Go WebSocket Tutorial&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h2&gt;Hello World&lt;/h2&gt; &lt;script&gt; let socket = new WebSocket("ws://127.0.0.1:8080/ws"); console.log("Attempting Connection..."); socket.onopen = () =&gt; { console.log("Successfully Connected"); socket.send("Hi From the Client!"); }; socket.onmessage = msg =&gt; { console.log(msg); }; socket.onclose = event =&gt; { console.log("Socket Closed Connection: ", event); socket.send("Client Closed!"); }; socket.onerror = error =&gt; { console.log("Socket Error: ", error); }; &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>nginx.conf</p> <pre><code> { server { listen 8080; server_name localhost; location /ws { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_pass http://localhost:8080/ws; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; } location / { # root html; # index index.html index.htm; proxy_pass http://localhost:8080; } } </code></pre> <p>I'm expecting the websocket connection to stay open indefinitely. I don't know what exactly is closing it and why.</p> <p>Any suggestions on what I'm doing wrong are much appreciated.</p> </div>

处理多个WebSocket连接

<div class="post-text" itemprop="text"> <p>I'm trying to create a program that will connect to several servers though gorilla web-sockets. I currently have a program that will iterate over a list of server addresses and create a new goroutine that will create its own Websocket.conn and handle reading and writing. </p> <p>The problem is that every time a new goroutine is created the previous goroutines are blocked and only the last one can continue. I believe this is because the gorilla websocket library is blocking each gorotutine, but I might be mistaken.</p> <p>I have tried putting a timer in the server list iterator and each goroutine will work perfectly but then the moment a new goroutine is made with another address the previous goroutine is blocked.</p> <p>The relevant bits of my code:</p> <p>In my <code>main.go</code></p> <pre class="lang-golang prettyprint-override"><code>for _, server := range servers { go control(ctx, server, port) } </code></pre> <p>In <code>control()</code></p> <pre class="lang-golang prettyprint-override"><code> func control(ctx context.Context, server, port string) { url := url.URL{ Scheme: "ws", Host: server + ":" + port, Path: "", } conn, _, err := websocket.DefaultDialer.Dial(url.String(), nil) if err != nil { panic(err) } defer conn.Close() go sendHandler(ctx, conn) go readHandler(ctx, conn) } readHandler(ctx context.Context, conn *websocket.Con) { for { _, p, err := conn.ReadMessage(); if err != nil { panic(err) } select { case &lt;-ctx.Done(): goto TERM default: // do nothing } } TERM: // do termination } sendHandler(ctx context.Context, conn *websocket.Con) { for _, msg := range msges { err = conn.WriteMessage(websocket.TextMessage, msg) if err != nil { panic(err) } } &lt;-ctx.Done() } </code></pre> <p>I removed the parts where I add waitgroups and other unnecessary pieces of code.</p> <p>So what I expect is for there to be 3n goroutines running (where n is the number of servers) without blocking but right now I see only 3 goroutines running which are the ones called by the last iteration of the server list.</p> <p>Thanks!</p> <p>EDIT 14/06/2019:</p> <p>I spent some time making a small working example and in the example the bug did not occur - none of the threads blocked each other. I'm still unsure what was causing it but here is my small working example:</p> <p><code>main.go</code></p> <pre class="lang-golang prettyprint-override"><code>package main import ( "context" "fmt" "os" "time" "os/signal" "syscall" "sync" "net/url" "github.com/gorilla/websocket" ) func main() { servers := []string{"5555","5556", "5557"} comms := make(chan os.Signal, 1) signal.Notify(comms, os.Interrupt, syscall.SIGTERM) ctx := context.Background() ctx, cancel := context.WithCancel(ctx) var wg sync.WaitGroup for _, server := range servers { wg.Add(1) go control(server, ctx, &amp;wg) } &lt;-comms cancel() wg.Wait() } func control(server string, ctx context.Context, wg *sync.WaitGroup) { fmt.Printf("Started control for %s ", server) url := url.URL { Scheme: "ws", Host: "0.0.0.0" + ":" + server, Path: "", } conn, _, err := websocket.DefaultDialer.Dial(url.String(), nil) if err != nil { panic(err) } defer conn.Close() var localwg sync.WaitGroup localwg.Add(1) go sendHandler(ctx, conn, &amp;localwg, server) localwg.Add(1) go readHandler(ctx, conn, &amp;localwg, server) &lt;- ctx.Done() localwg.Wait() wg.Done() return } func sendHandler(ctx context.Context, conn *websocket.Conn, wg *sync.WaitGroup, server string) { for i := 0; i &lt; 50; i++ { err := conn.WriteMessage(websocket.TextMessage, []byte("ping")) if err != nil { panic(err) } fmt.Printf("sent msg to %s ", server) time.Sleep(1 * time.Second) } &lt;- ctx.Done() wg.Done() } func readHandler(ctx context.Context, conn *websocket.Conn, wg *sync.WaitGroup, server string) { for { select { case &lt;- ctx.Done(): wg.Done() return default: _, p, err := conn.ReadMessage() if err != nil { wg.Done() fmt.Println("done") } fmt.Printf("Got [%s] from %s ", string(p), server) } } } </code></pre> <p>I tested it with dpallot's <a href="https://github.com/dpallot/simple-websocket-server" rel="nofollow noreferrer">simple-websocket-server</a> by a server on 5555, 5556 and 5557 respectively.</p> </div>

为什么在传输多个文件时WebSocket的实现要比HTTP / 2推送慢? (Node.js / Go)

<div class="post-text" itemprop="text"> <p>I've been experiment with WebSockets and HTTP/2 libraries in Node and Go. My basic setup is to create a client and server, repeatedly send a file from the server and measure the time until each file is available at the client.</p> <p>To my surprise, the HTTP/2 Push implementation performs significantly better than WebSocket (more than 5x faster in total time). Am I doing something wrong?</p> <p>My <a href="https://github.com/gorilla/websocket" rel="nofollow noreferrer">Gorilla WebSocket</a> and <a href="https://github.com/websockets/ws" rel="nofollow noreferrer">node-ws</a> servers below:</p> <p><strong>Go</strong></p> <pre><code>package main import ( "net/http" "io/ioutil" "log" "github.com/gorilla/websocket" ) var file []byte var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } func handler(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Fatal(err) } for i := 0; i &lt; 100; i++ { conn.WriteMessage(2, file) } } func main() { file, _ = ioutil.ReadFile("&lt;path-to-file&gt;") http.HandleFunc("/", handler) err := http.ListenAndServeTLS(":443", "&lt;path-to-cert&gt;", "&lt;path-to-key&gt;", nil) if err != nil { panic("ListenAndServe: " + err.Error()) } } </code></pre> <p><strong>Node</strong></p> <pre><code>const WebSocket = require('ws'); const https = require('https'); const fs = require('fs'); const options = { key: fs.readFileSync('&lt;path-to-key&gt;'), cert: fs.readFileSync('&lt;path-to-cert&gt;') }; var file = fs.readFileSync('&lt;path-to-file&gt;') var httpServer = new https.createServer(options).listen(443); var wss = new WebSocket.Server({ server: httpServer, perMessageDeflate: false }); wss.on('connection', function(ws) { for (let i = 0; i &lt; repetition; i++) { ws.send(file); } }); </code></pre> </div>

发送带有标题文本的二进制数据

<div class="post-text" itemprop="text"> <p>I am making a service in Golang &amp; Gorilla WebSocket which will convert speech to text, by using Microsoft Bing speech service. For reference </p> <p><a href="https://docs.microsoft.com/en-us/azure/cognitive-services/speech/api-reference-rest/websocketprotocol" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/azure/cognitive-services/speech/api-reference-rest/websocketprotocol</a></p> <p>javascript implementation</p> <p><a href="https://github.com/Azure-Samples/SpeechToText-WebSockets-Javascript" rel="nofollow noreferrer">https://github.com/Azure-Samples/SpeechToText-WebSockets-Javascript</a></p> <p>Here we need to send text data as well as audio data with headers. I am able to send text data but unable to send audio binary data with headers. </p> <p>Please suggest me how to send data</p> <p>Thanks Dinesh Gupta</p> </div>

b/s中,websocket心跳,断开重启服务器后,多个用户重连,为什么后台open方法接收的用户ID参数是相同的?

如图,重连发起连接时,session是不一样的,线程不是同一个,且确定不是一个页面发起的,ID是不一样的,为什么到后台就一样了,求大神一解 ![图片说明](https://img-ask.csdn.net/upload/201810/11/1539243550_593857.png) ![图片说明](https://img-ask.csdn.net/upload/201810/11/1539243558_587508.png) ![图片说明](https://img-ask.csdn.net/upload/201810/11/1539243565_183855.png) ![图片说明](https://img-ask.csdn.net/upload/201810/11/1539243585_904419.png) ![图片说明](https://img-ask.csdn.net/upload/201810/11/1539243611_632117.png) 如图,重连发起连接时,session是不一样的,线程不是同一个,且确定不是一个页面发起的,ID是不一样的,为什么到后台就一样了,求大神一解

为什么会收到错误消息“ http:response.Write on hijacked connection”?

<div class="post-text" itemprop="text"> <p>I am trying out the gorilla websocket library to get a feel of how websockets work with Go. But I keep getting this error message when I hit refresh button on the browser.</p> <p>When I reload the web page that I am using to test the websocket, I get these error messages on the Go console:</p> <pre><code>2015/09/18 19:04:41 websocket: close 1001 2015/09/18 19:04:41 http: response.Write on hijacked connection </code></pre> <p>The first one is status code for "going away". I am assuming it is because when I hit refresh it goes away from the websocket connection so that makes sense to me.</p> <p>But then I get an error message that I don't understand. The hijacked one. Why do I get it and what does it mean?</p> <p>I am running my code on localhost:8080 on a windows machine.</p> <p>The code I am using:</p> <pre><code>func wsHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) error { conn, err := websocket.Upgrade(w, r, nil, 1024, 1024) if err != nil { return err } defer conn.Close() for { _, msg, err := conn.ReadMessage() if err != nil { return err } log.Println(string(msg)) } return nil } </code></pre> <p>Client side:</p> <pre><code>var conn = new WebSocket("ws://localhost:8080/api/messages/websocket"); conn.onclose = function (e) { console.log("onclose fired"); }; conn.onopen = function (e) { console.log("onopen fired"); }; conn.onmessage = function (e) { console.log(e.data); }; setTimeout(function () { conn.send("foo!"); }, 1500); </code></pre> <p>When I load the page first time, only <code>foo!</code> is outputted to the console. So all in all, after loading the page once, and then reloading it twice I get an output like this:</p> <pre><code>2015/09/18 19:04:39 foo! 2015/09/18 19:04:41 websocket: close 1001 2015/09/18 19:04:41 http: response.Write on hijacked connection 2015/09/18 19:04:43 foo! 2015/09/18 19:04:44 websocket: close 1001 2015/09/18 19:04:44 http: response.Write on hijacked connection 2015/09/18 19:04:46 foo! </code></pre> <p>What does this mean? I'm I doing something wrong?</p> </div>

Python数据挖掘简易入门

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

HoloLens2开发入门教程

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

2019 Python开发者日-培训

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

Only老K说-爬取妹子图片(简单入门)

安装第三方请求库 requests 被网站禁止了访问 原因是我们是Python过来的 重新给一段 可能还是存在用不了,使用网页的 编写代码 上面注意看匹配内容 User-Agent:请求对象 AppleWebKit:请求内核 Chrome浏览器 //请求网页 import requests import re //正则表达式 就是去不规则的网页里面提取有规律的信息 headers = { 'User-Agent':'存放浏览器里面的' } response = requests.get

2020_五一数学建模_C题_整理后的数据.zip

该数据是我的程序读取的数据,仅供参考,问题的解决方案:https://blog.csdn.net/qq_41228463/article/details/105993051

R语言入门基础

本课程旨在帮助学习者快速入门R语言: 课程系统详细地介绍了使用R语言进行数据处理的基本思路和方法。 课程能够帮助初学者快速入门数据处理。 课程通过大量的案例详细地介绍了如何使用R语言进行数据分析和处理 课程操作实际案例教学,通过编写代码演示R语言的基本使用方法和技巧

人才招聘系统PHP+MySQL源码

PHP 5.0及以上 + MySQL 5.0及以上 开发的人才招聘系统完全可运行源码,按照操作说明简单配置即可运行。学习PHPWEB应用的完整系统程序源码。

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

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

python可视化分析(matplotlib、seaborn、ggplot2)

python可视化分析总结(matplotlib、seaborn、ggplot)一、matplotlib库1、基本绘图命令3、图形参数设置4、特殊统计图的绘制4.1 数学函数图4.2 气泡图4.1 三维曲面图二、seaborn库1、常用统计图1.1 箱线图1.2 小提琴图1.3 点图1.4 条图与计数图1.5 分组图1.6 概率分布图2、联合图3、配对图三、ggplot库1、图层画法+常用图形2、快速绘图 一、matplotlib库 1、基本绘图命令 import matplotlib.pyplot as

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

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

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

课程主要面向嵌入式Linux初学者、工程师、学生 主要从一下几方面进行讲解: 1.linux学习路线、基本命令、高级命令 2.shell、vi及vim入门讲解 3.软件安装下载、NFS、Samba、FTP等服务器配置及使用

人工智能-计算机视觉实战之路(必备算法+深度学习+项目实战)

系列课程主要分为3大阶段:(1)首先掌握计算机视觉必备算法原理,结合Opencv进行学习与练手,通过实际视项目进行案例应用展示。(2)进军当下最火的深度学习进行视觉任务实战,掌握深度学习中必备算法原理与网络模型架构。(3)结合经典深度学习框架与实战项目进行实战,基于真实数据集展开业务分析与建模实战。整体风格通俗易懂,项目驱动学习与就业面试。 建议同学们按照下列顺序来进行学习:1.Python入门视频课程 2.Opencv计算机视觉实战(Python版) 3.深度学习框架-PyTorch实战/人工智能框架实战精讲:Keras项目 4.Python-深度学习-物体检测实战 5.后续实战课程按照自己喜好选择就可以

【大总结2】大学两年,写了这篇几十万字的干货总结

本文十天后设置为粉丝可见,喜欢的提前关注 不要白嫖请点赞 不要白嫖请点赞 不要白嫖请点赞 文中提到的书我都有电子版,可以评论邮箱发给你。 文中提到的书我都有电子版,可以评论邮箱发给你。 文中提到的书我都有电子版,可以评论邮箱发给你。 本篇文章应该算是Java后端开发技术栈的,但是大部分是基础知识,所以我觉得对任何方向都是有用的。 1、数据结构 数据结构是计算机存储、...

lena全身原图(非256*256版本,而是全身原图)

lena全身原图(非256*256版本,而是全身原图) lena原图很有意思,我们通常所用的256*256图片是在lena原图上截取了头部部分的256*256正方形得到的. 原图是花花公子杂志上的一个

【项目实战】 图书信息管理系统(Maven,mybatis)(第一个自己独立完成的项目)

《程序设计综合训练实践报告》 此项目为图书信息管理系统,是一个采用了mysql+mybatis框架+java编写的maven项目

图书管理系统(Java + Mysql)我的第一个完全自己做的实训项目

图书管理系统 Java + MySQL 完整实训代码,MVC三层架构组织,包含所有用到的图片资源以及数据库文件,大三上学期实训,注释很详细,按照阿里巴巴Java编程规范编写

Python入门视频精讲

Python入门视频培训课程以通俗易懂的方式讲解Python核心技术,Python基础,Python入门。适合初学者的教程,让你少走弯路! 课程内容包括:1.Python简介和安装 、2.第一个Python程序、PyCharm的使用 、3.Python基础、4.函数、5.高级特性、6.面向对象、7.模块、8.异常处理和IO操作、9.访问数据库MySQL。教学全程采用笔记+代码案例的形式讲解,通俗易懂!!!

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

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

2018年全国大学生计算机技能应用大赛决赛 大题

2018年全国大学生计算机技能应用大赛决赛大题,程序填空和程序设计(侵删)

MySQL数据库从入门到实战应用

限时福利1:购课进答疑群专享柳峰(刘运强)老师答疑服务 限时福利2:购课后添加学习助手(微信号:csdn590),按消息提示即可领取编程大礼包! 为什么说每一个程序员都应该学习MySQL? 根据《2019-2020年中国开发者调查报告》显示,超83%的开发者都在使用MySQL数据库。 使用量大同时,掌握MySQL早已是运维、DBA的必备技能,甚至部分IT开发岗位也要求对数据库使用和原理有深入的了解和掌握。 学习编程,你可能会犹豫选择 C++ 还是 Java;入门数据科学,你可能会纠结于选择 Python 还是 R;但无论如何, MySQL 都是 IT 从业人员不可或缺的技能! 【课程设计】 在本课程中,刘运强老师会结合自己十多年来对MySQL的心得体会,通过课程给你分享一条高效的MySQL入门捷径,让学员少走弯路,彻底搞懂MySQL。 本课程包含3大模块:&nbsp; 一、基础篇: 主要以最新的MySQL8.0安装为例帮助学员解决安装与配置MySQL的问题,并对MySQL8.0的新特性做一定介绍,为后续的课程展开做好环境部署。 二、SQL语言篇: 本篇主要讲解SQL语言的四大部分数据查询语言DQL,数据操纵语言DML,数据定义语言DDL,数据控制语言DCL,学会熟练对库表进行增删改查等必备技能。 三、MySQL进阶篇: 本篇可以帮助学员更加高效的管理线上的MySQL数据库;具备MySQL的日常运维能力,语句调优、备份恢复等思路。 &nbsp;

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

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

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

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

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

太惨了,面试又被吊打

专为程序员设计的数学课

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

Eclipse archetype-catalog.xml

Eclipse Maven 创建Web 项目报错 Could not resolve archetype org.apache.maven.archetypes:maven-archetype-web

使用TensorFlow+keras快速构建图像分类模型

课程分为两条主线: 1&nbsp;从Tensorflow的基础知识开始,全面介绍Tensorflow和Keras相关内容。通过大量实战,掌握Tensorflow和Keras经常用到的各种建模方式,参数优化方法,自定义参数和模型的手段,以及对训练结果评估与分析的技巧。 2&nbsp;从机器学习基础算法开始,然后进入到图像分类领域,使用MNIST手写数据集和CIFAR10图像数据集,从简单神经网络到深度神经网络,再到卷积神经网络,最终完成复杂模型:残差网络的搭建。完成这条主线,学员将可以自如地使用机器学习的手段来达到图像分类的目的。

Python代码实现飞机大战

文章目录经典飞机大战一.游戏设定二.我方飞机三.敌方飞机四.发射子弹五.发放补给包六.主模块 经典飞机大战 源代码以及素材资料(图片,音频)可从下面的github中下载: 飞机大战源代码以及素材资料github项目地址链接 ————————————————————————————————————————————————————————— 不知道大家有没有打过飞机,喜不喜欢打飞机。当我第一次接触这个东西的时候,我的内心是被震撼到的。第一次接触打飞机的时候作者本人是身心愉悦的,因为周边的朋友都在打飞机, 每

最近面试Java后端开发的感受:如果就以平时项目经验来面试,通过估计很难,不信你来看看

在上周,我密集面试了若干位Java后端的候选人,工作经验在3到5年间。我的标准其实不复杂:第一能干活,第二Java基础要好,第三最好熟悉些分布式框架,我相信其它公司招初级开发时,应该也照着这个标准来面的。 我也知道,不少候选人能力其实不差,但面试时没准备或不会说,这样的人可能在进团队干活后确实能达到期望,但可能就无法通过面试,但面试官总是只根据面试情况来判断。 但现实情况是,大多数人可能面试前没准备,或准备方法不得当。要知道,我们平时干活更偏重于业务,不可能大量接触到算法,数据结构,底层代码这类面试必问

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

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

微信小程序开发实战之番茄时钟开发

微信小程序番茄时钟视频教程,本课程将带着各位学员开发一个小程序初级实战类项目,针对只看过官方文档而又无从下手的开发者来说,可以作为一个较好的练手项目,对于有小程序开发经验的开发者而言,可以更好加深对小程序各类组件和API 的理解,为更深层次高难度的项目做铺垫。

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

原价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)构建自己的论文网站案例

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

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

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

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

winfrom中嵌套html,跟html的交互

winfrom中嵌套html,跟html的交互,源码就在里面一看就懂,很简单

董付国老师Python全栈学习优惠套餐

购买套餐的朋友可以关注微信公众号“Python小屋”,上传付款截图,然后领取董老师任意图书1本。

程序员的算法通关课:知己知彼(第一季)

【超实用课程内容】 程序员对于算法一直又爱又恨!特别是在求职面试时,算法类问题绝对是不可逃避的提问点!本门课程作为算法面试系列的第一季,会从“知己知彼”的角度,聊聊关于算法面试的那些事~ 【哪些人适合学习这门课程?】 求职中的开发者,对于面试算法阶段缺少经验 想了解实际工作中算法相关知识 在职程序员,算法基础薄弱,急需充电 【超人气讲师】 孙秀洋&nbsp;| 服务器端工程师 硕士毕业于哈工大计算机科学与技术专业,ACM亚洲区赛铜奖获得者,先后在腾讯和百度从事一线技术研发,对算法和后端技术有深刻见解。 【课程如何观看?】 PC端:https://edu.csdn.net/course/detail/27272 移动端:CSDN 学院APP(注意不是CSDN APP哦) 本课程为录播课,课程无限观看时长,但是大家可以抓紧时间学习后一起讨论哦~

Java调用微信支付

Java 使用微信支付 一. 准备工作 1.

2020数模五一竞赛题目.rar

2020数模五一竞赛题目,附件、原题文件

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