将Websocket消息发送到Go中的特定客户端(使用Gorilla)

I am very new to Go and have found myself working with sockets as my first project. This is a redundant question, but I have failed to understand how to send a websocket update to a specific client in Go (using Gorilla).

The broad problem that I am trying to solve is - Building a typeahead using websockets and a search engine like ES/Lucene. I have maintained a bunch of indexes on my search engine and have a Go wrapper around it. When I started working on using websockets in Go, I have been finding almost all the examples showing broadcasting mechanism. When I tried to dig into this and tried to modify the example given in Gorilla's github repo based on the examples given in this thread and in this answer, I don't seem to understand connections and how does that fit in client.go

Ideally, the way I would like to see this working is -

  • A socket connection between the client and server is established
  • Upon the client sending inputs via the socket, the server fetches it and throws into into a channel (Go channel)
  • The indexing wrapper checks for this channel, and once there is something to fetch, the index is retrieved and written back to the socket

How can the server uniquely identify the Client?

I have used the examples given on Gorilla's Github repo

From my codebase hub.go has the following

type Hub struct {
    // Registered clients.
    clients map[*Client]bool

    // Inbound messages from the clients.
    broadcast chan []byte

    // Register requests from the clients.
    register chan *Client

    // Unregister requests from clients.
    unregister chan *Client

    connections map[string]*connection
}

func newHub() *Hub {
    return &Hub{
        broadcast:  make(chan []byte),
        register:   make(chan *Client),
        unregister: make(chan *Client),
        clients:    make(map[*Client]bool),
        connection: make(map[*Client]bool), // is this alright?
    }
}

func (h *Hub) run() {
    for {
        select {
        case client := <-h.register:
            h.clients[client] = true
        case client := <-h.unregister:
            if _, ok := h.clients[client]; ok {
                delete(h.clients, client)
                close(client.send)
            }
        case message := <-h.broadcast:
            for client := range h.connections {
                select {
                case client.send <- message:
                default:
                    close(client.send)
                    delete(h.connections, client)
                }
            }
        }
    }
}

and I am unsure with what I should be adding to client.go

type Client struct {
    // unique ID for each client
    // id string

    // Hub object
    hub *Hub

    // The websocket connection.
    conn *websocket.Conn

    // Buffered channel of outbound messages.
    send chan []byte

    // connection --> (what should the connection property be?)
    connection string
}

Please note - I will be adding an Id field within the Client struct. How can I proceed from here?

duandou8120
duandou8120 嗯,让我看一次这个例子。不久将在此线程上更新。谢谢@ThunderCat
一年多之前 回复
dtgta48604
dtgta48604 感谢您的建议,希望此编辑可以使事情更清晰
一年多之前 回复
dornc9470
dornc9470 我应该在数据库中维护客户的地图吗?Client结构不具备必要的内容来唯一地标识客户吗?
一年多之前 回复
dongshi949737
dongshi949737 问题是找到*Client
一年多之前 回复

1个回答

The chat example shows how to implement broadcast. The chat example is not a good starting point for an application if broadcast is not required.

To send a message to a specific websocket connection, simply write to the connection using NextWriter or WriteMessage. These methods do not support concurrent writers, so you may need to use a mutex or goroutine to ensure a single writer.

The simple approach for finding a specific *websocket.Connection is to pass *websocket.Connection to the code that needs it. If the application needs to associate other state with a connection, then define a type to hold that state and pass a pointer to that around:

type Client struct {
    conn *websocket.Conn
    mu sync.Mutex
    ...
}

The Hub can be modified to send messages to specific connection, but it's a roundabout path if broadcast is not needed. Here's how to do it:

Add ID field to client:

 ID idType // replace idType with int, string, or whatever you want to use

Change the Gorilla hub field from connections map[*connection]bool to connections map[idType]*connection.

Define a message type containing the message data and the ID of the target client:

type message struct {
   ID idtype
   data []byte
}

Replace the hub broadcast field with:

   send chan message

Change the hub for loop to:

for {
    select {
    case client := <-h.register:
        h.clients[client.ID] = client
    case client := <-h.unregister:
        if _, ok := h.clients[client.ID]; ok {
            delete(h.clients, client.ID)
            close(client.send)
        }
    case message := <-h.send:
        if client, ok := h.clients[message.ID]; ok {
            select {
            case client.send <- message.data:
            default:
                close(client.send)
                delete(h.connections, client)
            }
        }
    }

Send messages to a specific client by creating a message with the appropriate ID:

   hub.send <- message{ID: targetID, data: data}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
将Websocket消息发送到Go中的特定频道(使用Gorilla)

<div class="post-text" itemprop="text"> <p>I am very new to Go and have found myself working with sockets as my first project. This is a redundant question, but I have failed to understand how to send a websocket update to a specific channel in Go (using Gorilla).</p> <p>I am using <a href="https://github.com/gorilla/websocket/blob/master/examples/chat/main.go" rel="nofollow noreferrer">code sample from this link</a></p> <p>this method. But failed to modify to send messages to specific channel.</p> <p>Here is my sample code <strong>main.go</strong></p> <pre><code>func main() { flag.Parse() hub := newHub() go hub.run() http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { fmt.Println(hub) serveWs(hub, w, r) }) err := http.ListenAndServe(*addr, nil) if err != nil { log.Fatal("ListenAndServe: ", err) } </code></pre> <p>}</p> <p>There is other two files called hub.go and client.go I think hub.go below here something could be done</p> <pre><code>return &amp;Hub{ broadcast: make(chan []byte), register: make(chan *Client), unregister: make(chan *Client), clients: make(map[*Client]bool), } </code></pre> <p>Please suggest what should I change from here? Thanks in advanced.</p> <p>****UPDATE**</p> <p>What I am trying to do is I have a socket server written in go. Now suppose we have many clients written in react listening on server with a specific url like wss://abc.com/wss1 or may be wss://abc.com/wss2</p> <p>Now if client wss1 send a message to server, server will emit this message all clients listening on url wss1 not wss2 and vice versa.</p> <p>Till now i have been able to do broadcast to all clients irrespective of wss1 or wss2. Hope I made it clear. </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>

Websocket发送到特定客户端而不是广播

<div class="post-text" itemprop="text"> <p>I'm trying to modify the gorilla chat example to to send a message to a specific client instead of broadcast. First I'm storing the specific client in the hub against it's Id.</p> <p><strong>Hub.go</strong></p> <pre><code>type Hub struct { Clients map[int]*Client // Changed this piece to store id (int) Broadcast chan []byte Register chan *Client Unregister chan *Client } func (h *Hub) Run() { for { select { case client := &lt;-h.Register: fmt.Println("hub client register") h.Clients[client.Id] = client case client := &lt;-h.Unregister: fmt.Println("hub client Unregister") fmt.Println(h.Clients[client.Id]) if h.Clients[client.Id] != nil { delete(h.Clients, client.Id) close(client.Send) } case message := &lt;-h.Broadcast: fmt.Println("to send to a specific client", string(message)) } } } </code></pre> <p><strong>Client</strong></p> <p>I've added a field Id int to Client to know which client has sent a message</p> <pre><code>type Client struct { Hub *Hub Conn *websocket.Conn Send chan []byte Id int // Id of the client, } func (c *Client) readPump() { defer func() { c.Hub.Unregister &lt;- c c.Conn.Close() }() c.Conn.SetReadLimit(maxMessageSize) c.Conn.SetReadDeadline(time.Now().Add(pongWait)) c.Conn.SetPongHandler(func(string) error { c.Conn.SetReadDeadline(time.Now().Add(pongWait)); return nil }) for { _, message, err := c.Conn.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)) fmt.Println("client read message", string(message), "from", c.Id) // {"to":512,"message":"Hi there."} c.Hub.Broadcast &lt;- message } } </code></pre> <p>What are the next steps to take to be able to send the message to a specific client instead of broadcasting.</p> <p>the message itself is coming as JSON from the client specifying 'to' indicating who to send and what message to send.</p> <pre><code>{"to":512,"message":"Hi there."} </code></pre> </div>

Websocket消息发送到特定房间-Golang Kataras / Iris

<div class="post-text" itemprop="text"> <p>I am trying to send Message to Particular Room, but it doesn't work and It sends message to all room along with my message being received twice from my name and with first chat room user name. Message from 1 Room is broadcasted to all Chat Room.</p> <p>I have used Example Code from here- <a href="https://github.com/kataras/iris/blob/master/_examples/websocket/secure/main.go" rel="nofollow noreferrer">https://github.com/kataras/iris/blob/master/_examples/websocket/secure/main.go</a>. and <a href="https://github.com/kataras/iris/blob/master/_examples/websocket/native-messages/main.go" rel="nofollow noreferrer">https://github.com/kataras/iris/blob/master/_examples/websocket/native-messages/main.go</a></p> <p>Below is the Code, I am using, that is giving me the error :</p> <pre><code> var myChatRoom = strconv.Itoa(room.ID) ws := websocket.New(websocket.Config{}) ws.OnConnection(func(c websocket.Connection) { c.Join(myChatRoom) c.To(myChatRoom).EmitMessage([]byte(user.(users).Username + " has Joined Chat!")) c.OnMessage(func(data []byte) { message := string(data) if message == "leave" { c.Leave(myChatRoom) c.To(myChatRoom).EmitMessage([]byte(user.(users).Username + " has Left Chat!")) return } c.To(myChatRoom).EmitMessage([]byte(user.(users).Username + ": " + message)) }) c.OnDisconnect(func() { fmt.Printf("Connection with ID: %s has been disconnected! ", c.ID()) }) }) </code></pre> <p>HTML Code:</p> <pre><code>&lt;div id="messages" style="border-width: 1px; border-style: solid; height: 200px;overflow:auto"&gt;&lt;/div&gt; &lt;input type="text" id="messageTxt" /&gt; &lt;button type="button" id="sendBtn"&gt;Send&lt;/button&gt; </code></pre> <p>Javascript Code:</p> <pre><code>&lt;script&gt; var messageTxt; var messages; var HOST = 'localhost' jQuery(function() { messageTxt = jQuery("#messageTxt"); messages = jQuery("#messages"); w = new WebSocket("ws://" + HOST + "/my_endpoint"); w.onopen = function() { console.log("Websocket connection enstablished"); }; w.onclose = function() { appendMessage(jQuery("&lt;div&gt;&lt;center&gt;&lt;h3&gt;Disconnected&lt;/h3&gt;&lt;/center&gt;&lt;/div&gt;")); }; w.onmessage = function(message) { console.log("Message Appended: " + message) appendMessage(jQuery("&lt;div&gt;" + message.data + "&lt;/div&gt;")); }; jQuery("#sendBtn").click(function() { w.send(messageTxt.val().toString()); messageTxt.val(""); }); }) function appendMessage(messageDiv) { messageDiv.appendTo(jQuery("#messages")); } &lt;/script&gt; </code></pre> <p><strong>Error:</strong></p> <ol> <li><p>It sends message to all ROOM and not specific Room.</p></li> <li><p>User who created room first automatically joins all the ROOM</p></li> <li><p>People sending message in other ROOM see their message being Repeated/cloned in their ROOM by "FirstUser" who created first room in chat. (Irrespective of whether he is member of the chat group or not)</p></li> </ol> <p><strong>Expecting:</strong></p> <ol> <li><p>People can send/receive message to only those room where they have joined.</p></li> <li><p>First User should not be able to join CHATRoom automatically.</p></li> <li><p>People should not see their message being repeated again with "FirstUser" name.</p></li> </ol> </div>

websocket发送信息到多个客户端是发完一个再发另一个的吗?

如果我的服务端不需要接受客户端的信息,当客户端请求后就不停的给客户端发消息,即使所有客户端都断开连接了,还在发,这种模式行吗,正常的websocket服务端是不是要判断客户端发来的信息来了解客户端的状态

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

python3实现websocket协议发送二进制数据给客户端的问题。

自己网上找了一个例子,在服务端,我只发送字符串给客户端的时候是正常的,但是当在字符串前面添加int16和int32一起发送回给客户端就报错了:WebSocket connection to 'ws://127.0.0.1:9000/' failed: One or more reserved bits are on: reserved1 = 1, reserved2 = 0, reserved3 = 1 客户端可以正确读取到前面的两个int数据 但是后面的字符串读取数据不全,而且客户端还报错。求大神帮忙解答下。非常感谢。 https://pan.baidu.com/s/1i7kZy8t 源码地址

Swoole将websocket数据从服务器发送到客户端

<div class="post-text" itemprop="text"> <p><strong>Hi all!</strong></p> <p>I use swoole for WebSockets.</p> <p><strong>I create clietn part:</strong></p> <pre><code>&lt;script&gt; var ws = new WebSocket('ws://site.ll:9502/?user=tester01'); ws.onmessage = function(evt) { console.log(evt.data); }; ws.onopen = function (event) { ws.send('test'); } &lt;/script&gt; </code></pre> <p><strong>Create WebServer part:</strong></p> <pre><code>$server = new swoole_websocket_server("127.0.0.1", 9502); $server-&gt;on("start", function ($server) { echo "Swoole http server is started at http://127.0.0.1:9502 "; }); $server-&gt;on('open', function($server, $req) { echo "connection open: {$req-&gt;fd} "; }); $server-&gt;on('message', function($server, $frame) { echo "received message: {$frame-&gt;data} "; $server-&gt;push($frame-&gt;fd, json_encode(["hello", "world"])); }); $server-&gt;on('close', function($server, $fd) { echo "connection close: {$fd} "; }); $server-&gt;start(); </code></pre> <p><strong>Create send from server part:</strong></p> <pre><code>$client = new swoole_client(SWOOLE_SOCK_TCP); if (!$client-&gt;connect('127.0.0.1', 9502, -1)) { exit("connect failed. Error: {$client-&gt;errCode} "); } $client-&gt;send("hello world "); echo $client-&gt;recv(); $client-&gt;close(); </code></pre> <p>I trying to create TCP server inside WebSocket server, just adding next part inside "on start" callback:</p> <pre><code>$server2 = new swoole_server("127.0.0.1", 9503); $server2-&gt;on('connect', function ($server2, $fd){ echo "connection open: {$fd} "; }); $server2-&gt;on('receive', function ($server2, $fd, $from_id, $data) { $server2-&gt;send($fd, "Swoole: {$data}"); $server2-&gt;close($fd); }); $server2-&gt;on('close', function ($server2, $fd) { echo "connection close: {$fd} "; }); $server2-&gt;start(); </code></pre> <p>But Just receive an error: </p> <blockquote> <p>Swoole\Server::__construct(): eventLoop has already been created. unable to create swoole_server.</p> </blockquote> <p>I need to send data from server to client. How can I do this? In workerman library I doing next: <a href="https://github.com/Shkarbatov/WebSocketPHPWorkerman/blob/master/worker.php" rel="nofollow noreferrer">https://github.com/Shkarbatov/WebSocketPHPWorkerman/blob/master/worker.php</a></p> </div>

WebSocket 服务端与客户端互发消息问题?

WebSocket 如果服务端不停的发消息给客户端,客户端处理消息又不停的给服务端发处理结果消息,这样会有什么问题?本人遇到的情况是如果服务端一直在发,就收不到客户端发的消息,是不是因为只有一个连接通道,服务端和客户端不能同时发?

Gorilla Websocket手动关闭客户端连接

<div class="post-text" itemprop="text"> <p>I try to close connect manual(use <a href="https://dwst.github.io/" rel="nofollow noreferrer">Dark WebSocket Terminal</a>),but the client tell me 1005 (No Status Rcvd)<br> Server:</p> <pre><code>ReadLoop: for { mt, message, err := c.ReadMessage() if err != nil { log.Println("read:", err) log.Println("messageType:", mt) if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) { log.Printf("error: %v", err) } c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) break ReadLoop } log.Printf("recv: %s", message) //do sth in here err = c.WriteMessage(mt, message) if err != nil { //WriteMessage wrong log.Println("write:", err) break ReadLoop } } </code></pre> <p>It is not work and show the expected outputting the following:</p> <pre><code>read: websocket: close 1005 (no status) messageType: -1 error: websocket: close 1005 (no status) </code></pre> <p>How should i go about this?</p> </div>

Golang WebSocket客户端

<div class="post-text" itemprop="text"> <p>I want to make client websocket connections to exertnal server each connection = goroutine and reader. I was looking informations on the internet but I found how to create server websocket tutorials. Can anyone be so kind and make a trivial example and walk me through. I am using standart golang libary <a href="https://golang.org/x/net/websocket" rel="nofollow">https://golang.org/x/net/websocket</a>.</p> <p>I created some code but when I closed one connection program exited with EOF information. I won't post the code because it's probably bad duo to the fact it was my first try.</p> <p>I know how to read/send message from websocket but I don't know how to create multiple connections.</p> <p>Any informations, examples would be appreciate, thanks for reading</p> </div>

GO Websocket向所有客户发送消息

<div class="post-text" itemprop="text"> <p>Everything works fine with this code (shortened it for better reading).</p> <p>When <code>Client1</code> sends a request to the Server, the Server responses to him instantly. But, the other clients can not see the response message.</p> <p>So I want to make it go further: When a client sends a request to the server, the server will response to all clients so that all clients can see the message.</p> <p>How can I do that? Any examples or nice tutorials for beginners?</p> <p>Thanks in advance!</p> <p>Server:</p> <pre><code>import ( "github.com/gorilla/websocket" ) func main() { http.Handle("/server", websocket.Handler(echoHandler)) } func echoHandler(ws *websocket.Conn) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { return } for { messageType, p, err := conn.ReadMessage() if err != nil { return } print_binary(p) // simple print of the message err = conn.WriteMessage(messageType, p); if err != nil { return } } } </code></pre> </div>

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

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

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

带有Web代理的Golang Gorilla Websocket

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

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>

websocket 用c++编写客户端的问题

用MFC CAsyncSocket这个类的socket与服务器connect之后, 我发送了头:Sec-WebSocket-Key,Sec-WebSocket-Version: 13 等内容 等取得了服务器返回的应答:Sec-WebSocket-Accept,Upgrade:Websocket等内容 应该是握手成功了。 之后我在用CAsyncSocket的send发送文本过去服务器就没有返回数据了,服务器也木有向我返回数据。是不是发送的数据要经过编码或者是什么? 请问有websocket 用c++编写客户端 示例代码吗?

向两个客户端发送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>

使用Websocket向客户端广播服务器端消息

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

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

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

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

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

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

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

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

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

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

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

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

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

150讲轻松搞定Python网络爬虫

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

cuda开发cutilDLL

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

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

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

Tensorflow与python3.7适配版本

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

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

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

专为程序员设计的数学课

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

实现简单的文件系统

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

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

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

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

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

MFC一站式终极全套课程包

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

C++语言基础视频教程

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

Java8零基础入门视频教程

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

HoloLens2开发入门教程

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

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

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

pokemmo的资源

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

test_head.py

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

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

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

2019 AI开发者大会

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

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

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

DirectX修复工具V4.0增强版

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

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

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

2019 Python开发者日-培训

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

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

太惨了,面试又被吊打

相关热词 c#中如何设置提交按钮 c#帮助怎么用 c# 读取合并单元格的值 c#带阻程序 c# 替换span内容 c# rpc c#控制台点阵字输出 c#do while循环 c#调用dll多线程 c#找出两个集合不同的
立即提问