webSocket客户端报302,不知道哪里写错了。

请看下面代码:

 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!doctype html>
<html>
 <head>
  <meta charset="UTF-8" content="text/html">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>基于Java服务端消息主动推送技术</title>
  <style type="text/css">
    *{
        margin:0;
        padding:0;
    }
    body{
        background:url("image/bg.jpg") no-repeat;
        background-size:cover;
    }
    .chatbox{
        width:700px;
        height:500px;
        margin:100px auto;
        font-size:12px;
        font-family:"微软雅黑";
        color:#666;
    }
    h1{
        text-align:center;
        font-size:30px;
        color:green;
        text-shadow:5px 10px 10px #111;
    }
    .chatbox .c_info{
        text-align:left;
        line-height:46px;
    }
    .inputText{
        height:30px;
        border:0;
        outline:none;
        text-indent:1em;
        font-size:14px;
        font-family:"微软雅黑";
        color:#61B52D;
        border: 1px solid #61B52D;
    }
    .btn{
        width:80px;
        text-indent:0;
        background:#9AD02D;
        color:#fff;
        margin-left: 10px;
    }

    .chatbox .c_message{
        width:97%;
        height:300px;
        overflow:auto;
        border:1px solid yellow;
        font-size:24px;
        color:#9DA791;
        padding-left:20px;
        box-shadow:2px 10px 10px #111;
        /* background: #EAF9BE; */
    }

    .chatbox .c_send{
        margin-top: 10px;
    }
  </style>
 </head>
 <body>
    <div class="chatbox">
        <h1>基于Java服务端消息主动推送技术</h1>
        <div class="c_info">
            服务器地址:<input type="text" value="localhost:8080/webSocket" id="addr" class="inputText" style="width:350px"/>
            用户名:<input type="text" value="Yinwq" id="userName" class="inputText"/>
            <input type="button" id="con" class="inputText btn" value="连接" />
        </div>
        <div class="c_message">

        </div>
        <div class="c_send">
            <input type="text" id="sendText" class="inputText" style="width:592px" />
            <input type="button" id="sendBtn" class="inputText btn" value="发送" />
        </div>
    </div>
 </body>
 <!-- 引入jquery类库 -->
 <script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
 <script type="text/javascript">
    var connected = false;
    var ws;
    $(function(){
        $(".c_send").hide();
        //1.判断浏览器是否支持webSocket
        if(window.WebSocket || window.MozWebSocket){
            printMsg("您的浏览器支持WebSocket,您可以尝试连接到聊天服务器!" , "OK");
        }else{
            printMsg("您的浏览器不支持WebSocket,您可以换其他浏览器!" , "ERROR");
            $("#con").attr("disabled","true");
        }
    })

    //打印信息
    function printMsg(msg,msgType){
        if(msgType == "OK"){
            msg = "<span style='color:green'>"+msg+"</span>";
        }
        if(msgType == "ERROR"){
            msg = "<span style='color:red'>"+msg+"</span>"
        }
        $(".c_message").append(msg + "<br/>");
    }

    //点击连接的时候触发事件
    $("#con").click(function(){
        if(connected){
            //已连接
            ws.send("["+$("#userName").val()+"]离开了聊天室");
            connected = false;
            ws.close();
        }else{//没有连接
            printMsg("正在准备连接,请稍等!", "");
            var url = "ws://"+ $("#addr").val();
            if("WebSocket" in window){
                //ws = new WebSocket(url);
                ws = new WebSocket('ws://localhost:8080/webSocket');
            }else if ("MozWebSocket" in window) {
                ws = new MozWebSocket(url);
            }

            //连接成功后设置连接状态
            connected = true;
            $("#con").val("断开");

            //注册事件
            ws.onopen = function(event){
                openWs(event);
            };
            ws.onmessage = function(event){
                msgWs(event);
            };
            ws.onclose = function(event){
                closeWs(event);
            };
            ws.onerror = function(event){
                errorWs(event);
            };

        }

    });

    //打开socket
    function openWs(event){
        printMsg("连接已建立...!", "OK"); //建立连接的时候
        ws.send("["+$("#userName")+"]进入了聊天室");
        $(".c_send").show();
    };

    //接收消息
    function msgWs(event){
        printMsg(evnet.data);
    };
    //关闭连接
    function closeWs(event){
        $("#con").val("连接");
        //隐藏发送div
        $(".c_send").hide();
    };
    //产生错误
    function errorWs(event){
        printMsg("与服务器连接错误.." , "ERROR");
    };
    //点击发送触发事件
    $("#sendBtn").click(function(){
        //获取发送内容
        var text = $("#sendText").val();
        ws.send($("#userName").val() + "说:" + text);
        $("#sendText").val("");//清空发送框
    });
 </script>
</html>

浏览器报错
图片说明

图片说明

2个回答

那要看server是什么了。看报错是server和client协议不匹配造成的。不过,没有完整的代码和环境,没有办法判断。

兄弟,解决了嘛?其实从网上复制的说的好像都不对,要加项目名的说,我透。。。

qq_45412136
qq_45412136 回复追逐丿: 要加项目名才行呢,ws//localhost:8080/项目名/websocket
大约一个月之前 回复
yinwq
追逐丿 太久远了,之前好像是写的一个demo,没成功
大约一个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
WebSocket客户端与Java的Socket服务器通信

客户端使用websocket,服务器使用Java Socket。客户端经过new webSocket(utl)之后,服务器端可以收到请求头,但是客户端的webSocket.readyState一直是0,没有连接成功,这个是因为什么呢?是不是因为服务器端不可以用Java Socket

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>

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

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

spring_websocket 客户端不能给服务器发消息

spring_websocket 链接上服务器后调用 send 方法没有向服务器发送请求 ![图片说明](https://img-ask.csdn.net/upload/201609/27/1474968492_820686.png)

Websocket客户端身份验证问题

<div class="post-text" itemprop="text"> <p>如何在基于GoogleWebSocket的聊天系统中对客户端进行身份验证,以便只有有效用户才能发送消息?我希望当客户端请求只在验证连接之后才进行连接。</p> <p><strong>服务器端代码:</strong></p> <pre><code> &lt;?php // prevent the server from timing out set_time_limit(0); include("database.php"); // include the web sockets server script (the server is started at the far bottom of this file) require 'class.PHPWebSocket.php'; // when a client sends data to the server function wsOnMessage($clientID, $message, $messageLength, $binary) { global $Server; $ip = long2ip( $Server-&gt;wsClients[$clientID][6] ); // check if message length is 0 if ($messageLength == 0 or trim($message)=='') { $Server-&gt;wsClose($clientID); return; } // check if either it is valid msg or not if (!(substr($message,0,5)=='12345')) { $Server-&gt;wsSend($clientID, "You are not a valid user so you can not send message."); $Server-&gt;wsClose($clientID); return; } //The speaker is the only person in the room. Don't let them feel lonely. if ( sizeof($Server-&gt;wsClients) == 1 ) { mysql_query( "INSERT INTO message VALUES ( null,1000000000,2000000000,'$message',null )") or die(mysql_error()); $Server-&gt;wsSend($clientID, "You are alone in chat room"); } else //Send the message to everyone but the person who said it foreach ( $Server-&gt;wsClients as $id =&gt; $client ) if ( $id != $clientID ) //------- $Server-&gt;wsSend($id, "Visitor $clientID ($ip) said \"$message\""); { mysql_query( "INSERT INTO message VALUES ( null,1000000000,2000000000,'$message',null )") or die(mysql_error()); $Server-&gt;wsSend($id, " ($ip) \"$message\""); } } // when a client connects function wsOnOpen($clientID) { global $Server; $ip = long2ip( $Server-&gt;wsClients[$clientID][6] ); $Server-&gt;log( "$ip ($clientID) has connected." ); //Send a join notice to everyone but the person who joined foreach ( $Server-&gt;wsClients as $id =&gt; $client ) if ( $id != $clientID ) $Server-&gt;wsSend($id, "Visitor $clientID ($ip) has joined the room."); } // when a client closes or lost connection function wsOnClose($clientID, $status) { global $Server; $ip = long2ip( $Server-&gt;wsClients[$clientID][6] ); $Server-&gt;log( "$ip ($clientID) has disconnected." ); //Send a user left notice to everyone in the room foreach ( $Server-&gt;wsClients as $id =&gt; $client ) $Server-&gt;wsSend($id, "Visitor $clientID ($ip) has left the room."); } // start the server $Server = new PHPWebSocket(); $Server-&gt;bind('message', 'wsOnMessage'); $Server-&gt;bind('open', 'wsOnOpen'); $Server-&gt;bind('close', 'wsOnClose'); // for other computers to connect, you will probably need to change this to your LAN IP or external IP, // alternatively use: gethostbyaddr(gethostbyname($_SERVER['SERVER_NAME'])) $Server-&gt;wsStartServer('127.0.0.1', 9300); ?&gt; </code></pre> <p><strong>客户端代码:</strong></p> <pre><code> &lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset='UTF-8' /&gt; &lt;style&gt; input, textarea {border:1px solid #CCC;margin:0px;padding:0px} #body {max-width:800px;margin:auto} #log {width:100%;height:400px} #message {width:100%;line-height:20px} &lt;/style&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="fancywebsocket.js"&gt;&lt;/script&gt; &lt;script&gt; var Server; function log( text ) { $log = $('#log'); //Add text to log $log.append(($log.val()?" ":'')+text); //Autoscroll $log[0].scrollTop = $log[0].scrollHeight - $log[0].clientHeight; } function send( text ) { Server.send( 'message', text ); } $(document).ready(function() { log('Connecting...'); Server = new FancyWebSocket('ws://127.0.0.1:9300'); $('#message').keypress(function(e) { if ( e.keyCode == 13 &amp;&amp; this.value ) { // ----- log( 'You: ' + this.value ); log( $('#name').val()+" ---&gt; " + this.value ); send( $('#key').val()+ $('#name').val()+" ---&gt; " + this.value); $(this).val(''); } }); //Let the user know we're connected Server.bind('open', function() { log( "Connected." ); }); //OH NOES! Disconnection occurred. Server.bind('close', function( data ) { log( "Disconnected." ); }); //Log any messages sent from server Server.bind('message', function( payload ) { log( payload ); }); Server.connect(); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id='body'&gt; &lt;textarea id='log' name='log' readonly='readonly'&gt;&lt;/textarea&gt; &lt;table width="100%" border="0"&gt; &lt;tr&gt; &lt;td align="center"&gt;&lt;label for="name"&gt;Enter Your Name:&lt;/label&gt;&lt;input type="text" name="name" id='name' &gt;&lt;label for="name"&gt;Enter Your Key:&lt;/label&gt;&lt;input type="text" name="key" id='key' &gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;br/&gt; &lt;label for="message"&gt;Enter Your Message:&lt;/label&gt;&lt;input type='text' id='message' name='message' /&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> </div>

Golang Websocket客户端关闭了连接

<div class="post-text" itemprop="text"> <p>I have a golang connection. If the client opened the connection the database change the online column to 1. Here is my code but I didnt implement the last thing. My question, how can I change the database column to 0 if the client closed the connection. How can I track the client, and catch the connection close? </p> <pre><code>package main import ( "golang.org/x/net/websocket" "fmt" "log" "net/http" "strconv" ) type Clients struct { webs *websocket.Conn clientAddr string id int } var ( ActiveClients = make(map[Clients]int) ) func Echo(ws *websocket.Conn){ var err error client := ws.Request().RemoteAddr sockCli := Clients{webs: ws, clientAddr: client, id: 0} ActiveClients[sockCli] = 1 for{ var reply string if err = websocket.Message.Receive(ws, &amp;reply); err != nil{ fmt.Println("Cant receive", err) break }else{ if sockCli.id == 0{ sockCli.id, err = strconv.Atoi(reply) } } if err = websocket.Message.Send(ws, "id:"+strconv.Itoa(sockCli.id)); err != nil{ fmt.Println("Cant send") } for cs, _ := range ActiveClients { if cs.id == 1{ if err = websocket.Message.Send(cs.webs, "asd"); err != nil { // we could not send the message to a peer log.Println("Could not send message to ", cs.clientAddr, err.Error()) } }else { fmt.Println("No") } } } } func main(){ http.Handle("/", websocket.Handler(Echo)) if err := http.ListenAndServe(":1234", nil); err != nil{ log.Fatal("ListenAndServe: ", err) } } </code></pre> </div>

spring boot websocket wss 客户端

1.目前需要做依据spring-websocket基础上的WSS的客户端,目前只实现了ws,不知道如何实现WSS 2. 创建连接的代码 //连接 public static boolean connection(String name, String host, int port) { String url = "wss://" + host + ":" + port + "/websocket/" + name; WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), handler(), url); manager.setAutoStartup(true); HttpHeaders httpHeaders = new HttpHeaders(); manager.setHeaders(httpHeaders); manager.start(); } //client @Bean public static StandardWebSocketClient client() { return new StandardWebSocketClient(); } 目前是不知道如何生成一个带TLS的StandardWebSocketClient,希望有人帮忙看看

Java实现Websocket客户端,Nginx服务器下无法建立连接。是什么原因?

Java实现Websocket客户端,去连接另外一个websocket服务器。 线下测试是可以的。 客户端在tomcat服务器下面 服务端在另外一个tomcat服务器下面 线上无法连接 多了一个ngnix的反向代理 客户端和服务端都在这nigix的代理下面 补充一点:线上ngnix代理下的websocket服务器。通过前端js是可以连接的 只有后端用java进行连接连接不上

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>

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

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

websocket 服务端 客户端连接

这是服务端代码:var express = require('express'), app = express(), server = require('http').createServer(app), io = require('socket.io').listen(server); app.use('/',express.static(__dirname+'/www')); //监听8021端口 server.listen(8021); io.on('connection', function (socket) { socket.on('foo', function(data){ console.log(data); }) }) html代码: <body> <div><input id="sendbtn" type="button" value="button" /></div> <script src="../socket.io/socket.io.js"></script> <script type="text/javascript"> var socket = io.connect(), button = document.getElementById('sendbtn'); button.click = function () { socket.emit('foo','hello'); } </script> </body> 二者无法建立连接,和html中socket.IO的位置可能没引对有关系吗

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>

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>

核心php中的websocket客户端

<div class="post-text" itemprop="text"> <p>I am trying to send data to PHP websocket server, although it sends the data but the data received is a garbage values. How can fix this to get correct values posted to websocket php server?</p> <p>Below is my websocket php client script</p> <pre><code>&lt;?php $host = 'example.com:9000/server.php'; //where is the websocket server $port = 9000; //ssl $local = "http://localhost/"; //url where this script run $data = json_encode(array("server_msg"=&gt; "1","device_id"=&gt; "DDD-123455678")); //data to be send $head = "GET / HTTP/1.1"." ". "Host: $host"." ". "Upgrade: websocket"." ". "Connection: Upgrade"." ". "Sec-WebSocket-Key: asdasdaas76da7sd6asd6as7d"." ". "Sec-WebSocket-Version: 13"." ". "Content-Length: ".strlen($data)." "." "; ////WebSocket handshake $sock = fsockopen($host, $port, $errno, $errstr, 2); fwrite($sock, $head ) or die('error:'.$errno.':'.$errstr); $headers = fread($sock, 2000); fwrite($sock, "\x00$data\xff" ) or die('error:'.$errno.':'.$errstr); $wsdata = fread($sock, 2000); //receives the data included in the websocket package "\x00DATA\xff" $retdata = trim($wsdata,"\x00\xff"); //extracts data ////WebSocket handshake fclose($sock); echo $retdata; ?&gt; </code></pre> <p>Thanks</p> <p>Hi, </p> <p>I have already tried it and it gives me error as below:</p> <p>Fatal error: Uncaught exception 'WebSocket\ConnectionException' with message 'Connection to 'ws://************/server.php' in /var/www/webclientphp/vendor/textalk/websocket/lib/Client.php on line 149</p> <p>WebSocket\ConnectionException: Connection to 'ws://************/server.php' failed: Server sent invalid upgrade response: HTTP/1.1 101 Web Socket Protocol Handshake Upgrade: websocket Connection: Upgrade WebSocket-Origin: ************ WebSocket-Location: ws://************:9000/demo/shout.php Sec-WebSocket-Accept:Kfh9QIsMVZcl6xEPYxPHzW8SZ8w= in /var/www/webclientphp/vendor/textalk/websocket/lib/Client.php on line 149</p> <p>Please help</p> </div>

WebSocket客户端身份验证方法

<div class="post-text" itemprop="text"> <p><strong>How to authenticate the client connecting to the websocket server?</strong></p> <p>In http we could use Oauth 2.0 to authenticate the user and the client too. But in websocket I am not able to understand how to do so.</p> <p>As far as I can understand for authentication of the user connecting we could just ask the client to send a message with a token to authenticate the user. But how to prevent an un-identified client to connect to the server?</p> <p><strong>Isn't there any header for token based authentication for websocket</strong> as that would allow for both the authentication simultaneously just as in any Oauth 2.0 Rest api authentication. </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客户端侦听Golang websocket服务器

<div class="post-text" itemprop="text"> <p>I am trying to post messages using Golang websocket and listen on Node client side.</p> <p>Here's part of code:</p> <p>Golang:</p> <pre><code>func NewUpgrader() *websocket.Upgrader { return &amp;websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, CheckOrigin: func(r *http.Request) bool { return true }, } func (s WebsocketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { upgrader := NewUpgrader() ws, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Errorf("websocket: could not upgrade %v", err) fmt.Fprintf(w, "websocket: could not upgrade %v", err) return } go func() { defer ws.Close() for msg := range s.Messages { json, _ := json.Marshal(msg) err := ws.WriteMessage(1, json) if err != nil { log.Errorf("websocket: error sending message: %v", err) } } }() </code></pre> <p>By doing this I can get all the messages when I run the code below on Google console </p> <p><code>ws = new WebSocket('ws://localhost:8080/ws') ws.onmessage = function(msg) { console.log(JSON.parse(msg.data)) }</code></p> <p>And I add the same two lines code on my client side, now I got these errors</p> <p>Golang side:</p> <p><code>INFO[0009] 400 GET localhost:8080/ws (0 bytes) id: 77b7355412f2ffcd ERRO[0009] websocket: could not upgrade websocket: not a websocket handshake: 'upgrade' token not found in 'Connection' header</code></p> <p>Client side(browser console):</p> <p><code>GET http://localhost:8080/ws 400 (Bad Request) Failed to load http://localhost:8080/ws: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4000' is therefore not allowed access. The response had HTTP status code 400. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. Uncaught (in promise) TypeError: Failed to fetch</code></p> <p>I tried to compare these two get request(Google console vs my client-side code). I found out that for google console there's a header <code>Connection:[Upgrade]</code>, but the header looks like this <code>Connection:[keep-alive]</code> in my client-side code.</p> <p>Not sure if this is the reason why I can not connect these two, any ideas?</p> <p>Thanks!</p> </div>

websocket server 返回给客户端数据报错

![图片说明](https://img-ask.csdn.net/upload/201611/03/1478166374_946184.png) 自己写了一个websocket server 客户端通过websocket 发送 111 给server, server 收到后返回111 给客户端, 客户端收到报错。 ![图片说明](https://img-ask.csdn.net/upload/201611/03/1478166687_970719.png) 是我组装的返回报文错了吗, 哪位大神帮忙看一下,谢谢!

WebSocket客户端如何知道一条消息已被完全读取?

<div class="post-text" itemprop="text"> <p>I used do it like:</p> <pre class="lang-golang prettyprint-override"><code> ... ws, err := websocket.Dial(url, "", origin) ... var buffer = make([]byte, 512) var rs = make([]byte, 0, 512) L: for { m, err := ws.Read(buffer) if err != nil { if err == io.EOF { break L } fmt.Println(err.Error()) return } rs = append(rs, buffer[:m]...) if m &lt; 512 { break L } } </code></pre> <p>This has a bug: if the message's length is exactly 512 or 1024 or 2048... the loop never breaks; it will be stuck at <code>ws.Read()</code> and wait without throwing <code>io.EOF</code>. </p> <p>Afterwards I observed that <code>ws.Len()</code> is always longer than the messages's length by 4.</p> <p>I rewrote the code as:</p> <pre class="lang-golang prettyprint-override"><code> var buffer = make([]byte, 512) var rs = make([]byte, 0, 512) var sum = 0 L: for { m, err := ws.Read(buffer) if err != nil { if err == io.EOF { break L } fmt.Println(err.Error()) return } rs = append(rs, buffer[:m]...) sum+=m if sum &gt;= ws.Len()-4 { break L } } </code></pre> <p>This way is okay.</p> <p>But the number <code>4</code> is a magic code.</p> <p>Is there a way to find the message's max length? </p> <p>Some friends suggest separating the message packet, but I think WebSocket should not consider packet stucking or separating.</p> <p>What is the most proper way for a WebSocket client to read a message?</p> </div>

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

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

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

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

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

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

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

数据结构与算法思维导图

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

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

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

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

Linux面试题(2020最新版)

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

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

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

和黑客斗争的 6 天!

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

大佬原来都是这样炼成的

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

立即提问
相关内容推荐