websocket 使用wss连接 5C

图片说明图片说明

        首先,我使用的是C#语言发布在iis,然后利用nxgin 使用证书,把它转成https,是没有问题的。 直接访问域名也可以访问这个iis下的网站,这个网站端口是20000.然后我使用ws:xx:xx:xx:4000连接是没有问题的,但是使用wss一直连接不了。为什么求助大神。

1个回答

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
.net 服务器 WebSocket wss无法连接

如题 跪求帮助 .net 服务器 WebSocket wss无法连接 出错WebSocket opening handshake timed out

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,希望有人帮忙看看

如何为wss连接创建websocket?

<div class="post-text" itemprop="text"> <p>I have the following code for connection to my websocket, but the problem is when the domain has an SSL certificate as it is my case, when I make the connection with ws everything works perfectly, but when I put the wss I get this error </p> <blockquote> <p>Error in connection establishment: net::ERR_SSL_PROTOCOL_ERROR</p> </blockquote> <p>index.js</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function(){ //create a new WebSocket object. var wsUri = "wss://dominio.com:9001/socket.php"; websocket = new WebSocket(wsUri); websocket.onopen = function(ev) { // connection is open var preg = { id: 303, historial: { titulo: 'Conexion al sistema', url: window.location.href } }; //convert and send data to server websocket.send(JSON.stringify(preg)); } //#### Message received from server? websocket.onmessage = function(ev) { var msg = JSON.parse(ev.data); //PHP sends Json data //alert(msg.user); console.log(JSON.stringify(msg)); if(msg.conexion){ var preg = { id: 303, estado: 1 }; //convert and send data to server websocket.send(JSON.stringify(preg)); }else{ //$("#res").load("cargar.php",{bloque:'session',array:msg}); } /* if(msg.user == 'system'){ //console.log(umsg); //preg=JSON.parse(umsg); var preg = { id: &lt;?=$_GET['u']?&gt;, recurso: msg.recurso, estado: msg.estado, historial: { titulo: 'Conexion al sistema', url: window.location.href } }; //convert and send data to server websocket.send(JSON.stringify(preg)); //$('#message_box').append("&lt;div class=\"system_msg\"&gt;"+umsg+"&lt;/div&gt;"); }*/ }; websocket.onerror = function(ev){}; websocket.onclose = function(ev){}; }); &lt;/script&gt; </code></pre> <p>and this is my php socket.php</p> <pre><code>&lt;?php $host = '0.0.0.0'; //host $port = '9001'; //port $null = NULL; //null var $json_general=array(); //Create TCP/IP sream socket $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); //reuseable port socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1); //bind socket to specified host socket_bind($socket, 0, $port); //$socket = stream_socket_client("ssl://localhost:9001", $errno, $errstr); //listen to port socket_listen($socket); //create &amp; add listning socket to the list $clients = array($socket); //start endless loop, so that our script doesn't stop while (true) { //manage multipal connections $changed = $clients; //returns the socket resources in $changed array socket_select($changed, $null, $null, 0, 10); //check for new socket if (in_array($socket, $changed)) { $socket_new = socket_accept($socket); //accpet new socket $clients[] = $socket_new; //add socket to client array $header = socket_read($socket_new, 1024); //read data sent by the socket perform_handshaking($header, $socket_new, $host, $port); //perform websocket handshake socket_getpeername($socket_new, $ip); //get ip address of connected socket //$response = mask(json_encode(array('user'=&gt;'system','tipo'=&gt;'0', 'destino'=&gt;'0', 'categoria'=&gt;'0', 'descripcion'=&gt;'', 'estado'=&gt;'Conectado','datos'=&gt;array('ip'=&gt;$ip, 'recurso'=&gt;''.$socket_new)))); $response = mask(json_encode(array('user'=&gt;'system', 'estado'=&gt;1,'ip'=&gt;$ip, 'recurso'=&gt;''.str_replace("Resource id #","",$socket_new)))); //$response = mask(json_encode(array('type'=&gt;'system', 'message'=&gt;$ip.' conectado'.$socket_new))); //prepare json data send_message($response); //notify all users about new connection //make room for new socket $found_socket = array_search($socket, $changed); unset($changed[$found_socket]); } //loop through all connected sockets foreach ($changed as $changed_socket) { //check for any incoming data while(socket_recv($changed_socket, $buf, 1024, 0) &gt;= 1) { $received_text = unmask($buf); //unmask data $tst_msg = json_decode($received_text, true); //json decode /*if(isset($tst_msg['conexion'])){ $pre=array(); foreach($json_general as $id =&gt; $dat){ $pre[$id]=array(); $pre[$id]['estado']=0; $pre[$id]['historial']=$dat['historial']; } $json_general=$pre; $response_text = mask(json_encode($tst_msg)); send_message($response_text); }*/ if(isset($tst_msg['id'])){ if(isset($json_general[$tst_msg['id']])){ //$json_general[$tst_msg['id']]=array(); if(isset($tst_msg['historial'])){ if(isset($json_general[$tst_msg['id']]['historial'])){ $q=count($json_general[$tst_msg['id']]['historial']); }else{ $json_general[$tst_msg['id']]['historial']=array(); $q=0; } $json_general[$tst_msg['id']]['historial'][$q]=array(); $json_general[$tst_msg['id']]['historial'][$q]=$tst_msg['historial']; $json_general[$tst_msg['id']]['historial'][$q]['fecha']=date("Y-m-d H:i:s"); } if($json_general[$tst_msg['id']]['estado']){ $json_general[$tst_msg['id']]['estado']=$tst_msg['estado']; } }else{ $json_general[$tst_msg['id']]=array(); $json_general[$tst_msg['id']]['historial'][0]=$tst_msg['historial']; $json_general[$tst_msg['id']]['historial'][0]['fecha']=date("Y-m-d H:i:s"); } if(isset($socket_new)){ $json_general[$tst_msg['id']]['recurso']=str_replace("Resource id #","",$socket_new); $json_general[$tst_msg['id']]['estado']=1; } } //prepare data to be sent to client $response_text = mask(json_encode($json_general)); //$response_text = mask(json_encode(array('type'=&gt;'usermsg', 'typem'=&gt;$user_type, 'name'=&gt;$user_name, 'message'=&gt;$user_message, 'color'=&gt;$user_color, 'tipo'=&gt;$tipo, 'entrada'=&gt;$entrada))); send_message($response_text); //send data break 2; //exist this loop } $buf = @socket_read($changed_socket, 1024, PHP_NORMAL_READ); if ($buf === false) { // check disconnected client // remove client for $clients array $found_socket = array_search($changed_socket, $clients); socket_getpeername($changed_socket, $ip); unset($clients[$found_socket]); //notify all users about disconnected connection //$response = mask(json_encode(array('user'=&gt;'system','tipo'=&gt;'0', 'destino'=&gt;'0', 'categoria'=&gt;'0', 'descripcion'=&gt;'', 'estado'=&gt;'Desconectado','datos'=&gt;array('ip'=&gt;$ip, 'recurso'=&gt;''.$socket_new)))); $response = mask(json_encode(array('user'=&gt;'system', 'estado'=&gt;0,'ip'=&gt;$ip, 'recurso'=&gt;''.str_replace("Resource id #","",$socket_new)))); foreach($json_general as $key =&gt; $dato){ if($dato['recurso']==str_replace("Resource id #","",$socket_new)){ //$json_general[$key]['estado']=0; } } //$response = mask(json_encode(array('type'=&gt;'system', 'message'=&gt;$ip.' desconectado'))); send_message($response); //envio de datos generales //$response_text = mask(json_encode($json_general)); $pre=array(); foreach($json_general as $id =&gt; $dat){ $pre[$id]=array(); $pre[$id]['estado']=0; $pre[$id]['historial']=$dat['historial']; } $json_general=$pre; $response_text = mask('{"conexion":1}'); send_message($response_text); } } } // close the listening socket socket_close($socket); function send_message($msg){ global $clients; foreach($clients as $changed_socket){ @socket_write($changed_socket,$msg,strlen($msg)); } return true; } //Unmask incoming framed message function unmask($text) { $length = ord($text[1]) &amp; 127; if($length == 126) { $masks = substr($text, 4, 4); $data = substr($text, 8); } elseif($length == 127) { $masks = substr($text, 10, 4); $data = substr($text, 14); } else { $masks = substr($text, 2, 4); $data = substr($text, 6); } $text = ""; for ($i = 0; $i &lt; strlen($data); ++$i) { $text .= $data[$i] ^ $masks[$i%4]; } return $text; } //Encode message for transfer to client. function mask($text) { $b1 = 0x80 | (0x1 &amp; 0x0f); $length = strlen($text); if($length &lt;= 125) $header = pack('CC', $b1, $length); elseif($length &gt; 125 &amp;&amp; $length &lt; 65536) $header = pack('CCn', $b1, 126, $length); elseif($length &gt;= 65536) $header = pack('CCNN', $b1, 127, $length); return $header.$text; } //handshake new client. function perform_handshaking($receved_header,$client_conn, $host, $port) { $headers = array(); $lines = preg_split("/ /", $receved_header); foreach($lines as $line) { $line = chop($line); if(preg_match('/\A(\S+): (.*)\z/', $line, $matches)) { $headers[$matches[1]] = $matches[2]; } } $secKey = $headers['Sec-WebSocket-Key']; $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'))); //hand shaking header $upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake " . "Upgrade: websocket " . "Connection: Upgrade " . "WebSocket-Origin: $host " . "WebSocket-Location: wss://$host:$port/demo/shout.php ". "Sec-WebSocket-Accept:$secAccept "; socket_write($client_conn,$upgrade,strlen($upgrade)); } </code></pre> </div>

在C++平台下,websocket 怎样弄才支持wss,现在的是ws可以

在C++平台下,websocket 怎样弄才支持wss协议,现在的是已经实现了支持ws协议, 怎么改可以即支持ws又支持Wss的

netty做服务端 websocket做客户端 实现wss协议

现在ws可以成功建立连接 但是wss不知到该怎么建立 请问有没有相关的demo

android- websocket连接“wss://ws.biki.com/kline-api/ws”时执行onOpen,但是send信息后没有返回值

//用的websocket版本: implementation "org.java-websocket:Java-WebSocket:1.4.0" String url = "wss://ws.biki.com/kline-api/ws"; WebSocketClient client = new WebSocketClient(new URI(url), new Draft_6455()); //发送订阅 服务端返回信息 client.send("{ \"event\": \"sub\", \"params\": { \"channel\": \"market_btcusdt_kline_1min\", \"cb_id\": \"aaaa\" } }");

求助!websocket连接后端一直不返回连接成功

前端 let wsuri= global.wsURL+"/slims/v1/websocket/"; if ("WebSocket" in window) { console.log("您的浏览器支持查看在线人数") } else { alert('当前浏览器不支持查看人员在线状态'); } this.websockt = new WebSocket(wsuri); this.websockt.onmessage = this.websocketonmessage; this.websockt.onerror = this.websocketonerror; this.websockt.onclose = this.websocketclose; this.websockt.onopen =this.websocketonopen; // Web Socket 已连接上,使用 send() 方法发送数据s console.log('数据发送中...') this.websockt.send('Holle') console.log('数据发送完成') } this.websockt.send = this.websocketsend; }, websocketonopen(){ //连接建立之后执行send方法发送数据 console.log("xxxx"); }, websocketonerror(){//连接建立失败重连 console.log("重新连接") this.initWebSocket(); }, websocketonmessage(e){ //数据接收 console.log("数据接收") }, websocketsend(Data){//数据发送 console.log("数据发送"); this.websockt .send("幸福9999");debugger alert(8888); }, websocketclose(e){//关闭连接 console.log("关闭连接") this.websockt.onclose(); }, }, 后台 : @OnOpen public void onOpen(Session session, EndpointConfig sce) throws IOException { this.session = session; //Object转换成Long Long uuid = Long.valueOf(String.valueOf(sce.getUserProperties().get("uuid"))); if (null == uuid) { onClose(); } webSocketSet.add(this); //线程安全的原子数+1 subOnlineCount(); System.out.println("有链接加入,当前人数为:" + getOnline_num()); this.session.getAsyncRemote().sendText("有链接加入,当前人数为:" + getOnline_num()); map.put(session, uuid); System.out.println("当前登录人uid" + uuid); String stats = "0"; //是首次登陆的人 if (0 == userSocketService.list(Condition.create().eq("uid", uuid)).size()) { UserSocket usersocket = new UserSocket(); usersocket.setUid(uuid); usersocket.setStats(stats); usersocket.setCompany_id(0L); userSocketService.saves(usersocket); } else { UserSocket usersocket = new UserSocket(); usersocket.setUid(uuid); usersocket.setStats("0"); userSocketService.update(usersocket, Condition.create().eq("uid", uuid)); } sendMessage("------------------------后台-----) 可以连接上,但是没法发消息,正常这里应该显示状态码是101的,但是一直显示在链接中明明后台已经收到请求了,到底是怎么回事呢? ![图片说明](https://img-ask.csdn.net/upload/201810/17/1539757022_269768.png)

Websocket over wss://断开连接而没有任何错误

<div class="post-text" itemprop="text"> <p>I am making a webcoket application for my website. Evrything were OK before I tried secured connection. Chrome just disconnects with "undefined" error. Server console shows</p> <blockquote> <p>2014-07-25 15:24:50 [info] [client 5.ХХХ.ХХХ.ХХХ:54166] Connected</p> <p>2014-07-25 15:24:50 [info] [client 5.ХХХ.ХХХ.ХХХ:54166] Disconnected</p> </blockquote> <p>My server is running CentOS 6 with Apache and PHP 5.4. For WS server I choose <a href="https://github.com/lemmingzshadow/php-websocket" rel="nofollow">Link1</a> Certificate also was built for TSL. What I am doing wrong? You can check it out on <a href="https://ws.d1xn.ru/en.php" rel="nofollow">Link2</a></p> </div>

TLS是否在整个wss连接中使用或仅在连接时使用?

<div class="post-text" itemprop="text"> <p>I plan to write an secure websocket server in golang. My question is:</p> <p>Is TLS used throughout the entire connection when using <code>wss://</code>, or is it just used when upgrade from http(s) to websocket protocol?</p> <p>The reason I ask is that as I understand the websocket protocol has nothing to do with http except that the connection is initiated via http(s).</p> <p>So, if I use <code>ListenAndServeTLS</code> in my Go program, can I ensure that the entire websocket conversation is secure?</p> </div>

手机浏览器websocket,无法连接一直error

``` var websocket = null; if ('WebSocket' in window) { websocket = new WebSocket("ws://localhost:8080/springws/websocket/socketServer.do"); } else if ('MozWebSocket' in window) { websocket = new MozWebSocket("ws://localhost:8080/springws/websocket/socketServer.do"); } else { websocket = new SockJS("http://localhost:8080/springws/sockjs/socketServer.do"); } websocket.onopen = onOpen; websocket.onmessage = onMessage; websocket.onerror = onError; websocket.onclose = onClose; ``` 一直是监听到error,请问有了解的吗。 电脑端浏览器是正常的,手机浏览器检测有WebSocket

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

为什么此websocket连接被拒绝?

<div class="post-text" itemprop="text"> <p>I try to use the slack-sample bot from this blogpost <a href="https://www.opsdash.com/blog/slack-bot-in-golang.html" rel="nofollow">https://www.opsdash.com/blog/slack-bot-in-golang.html</a> . I've successfully created my api token, but i can not connect to the websocket server (the rtm.start request passs normally). I've get the error message</p> <blockquote> <pre><code>dial tcp 54.242.95.213:443: connectex: No connection could be made because the target machine actively refused it </code></pre> </blockquote> <p>I've also tried to connect via a chrome app called <strong>Simple Web Socket Client</strong> and via a website based one tester. Both work well, i can establish a connection and i can send data.</p> <p>I'm behind a proxy, but i only have troubles with golang's websocket.Dial function.</p> <p>Does anybody know why this can happen?</p> <p>I use:<br> - Windows 7 SP1 x64<br> - Golang 1.7.1 windows/amd64 </p> <p>Greetings Tonka</p> </div>

使用wss://时,Websockets和https不会连接

<div class="post-text" itemprop="text"> <p>i am creating a php web chat app for my site, it is built in php and js html, it works fine (with some minor annoyances and needing updates) when it is used over http (in secure connections) but when i use https it asked about loading unsafe scripts (the main js for the system) which i dont want, i have tried to change it to wss:// but now i dont get any connection now, there is two main parts to the site the page and the server, the page is as follows</p> <pre><code>&lt;style type="text/css"&gt; &lt;!-- .chat_wrapper { width: 100%; height: 100%; margin-right: auto; margin-left: auto; background: #CCCCCC; border: 1px solid #999999; padding: 10px; font: 12px 'lucida grande',tahoma,verdana,arial,sans-serif; } .chat_wrapper .message_box { background: #FFFFFF; height: 380px; overflow: scroll; padding: 10px; border: 1px solid #999999; } .chat_wrapper .panel input{ padding: 2px 2px 2px 5px; } .system_msg{color: #BDBDBD;font-style: italic;} .user_name{font-weight:bold;} .user_message{color: #88B6E0;} --&gt; &lt;/style&gt; &lt;?php $colours = array('007AFF','FF7000','FF7000','15E25F','CFC700','CFC700','CF1100','CF00BE','F00'); $user_colour = array_rand($colours); ?&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"&gt;&lt;/script&gt; &lt;script language="javascript" type="text/javascript"&gt; $(document).ready(function(){ $("#message").keyup(function(event){ if(event.keyCode == 13){ $("#send-btn").click(); } }); //create a new WebSocket object. var wsUri = "ws://radiobeacononline.com:9000/server.php"; websocket = new WebSocket(wsUri); websocket.onopen = function(ev) { // connection is open var myname = $('#name').val(); //get user name var mypic = $('#pic').val(); var msg = { message: 'has just joined the chat', name: myname, pic : mypic, color : '&lt;?php echo $colours[$user_colour]; ?&gt;' }; //convert and send data to server websocket.send(JSON.stringify(msg)); $('#message_box').append("&lt;div class=\"system_msg\"&gt;Connected!&lt;/div&gt;"); //notify user } $('#send-btn').click(function(){ //use clicks message send button var mymessage = $('#message').val(); //get message text var myname = $('#name').val(); //get user name if(mymessage == ""){ //emtpy message? alert("Enter Some message Please!"); return; } var mypic = $('#pic').val(); //prepare json data var msg = { //type : 'mesage', message: mymessage, name: myname, pic : mypic, color : '&lt;?php echo $colours[$user_colour]; ?&gt;' }; //convert and send data to server websocket.send(JSON.stringify(msg)); }); //#### Message received from server? websocket.onmessage = function(ev) { var msg = JSON.parse(ev.data); //PHP sends Json data var type = msg.type; //message type var umsg = msg.message; //message text var uname = msg.name; //user name var upic = msg.pic // user pic var ucolor = msg.color; //color if(type == 'usermsg') { $('#message_box').append("&lt;div&gt;&lt;span class=\"user_name\" style=\"color:#"+ucolor+"\"&gt;&lt;img src=\"app/engine/storage/users/"+uname+"/profile/"+upic+"\" width=\"23\" height=\"23\"&gt;"+uname+"&lt;/span&gt; : &lt;span class=\"user_message\"&gt;"+umsg+"&lt;/span&gt;&lt;/div&gt;"); } if(type == 'system') { $('#message_box').append("&lt;div class=\"system_msg\"&gt;"+umsg+"&lt;/div&gt;"); } $('#message').val(''); //reset text }; window.setInterval(function() { var elem = document.getElementById('message_box'); elem.scrollTop = elem.scrollHeight; }, 500); websocket.onerror = function(ev){$('#message_box').append("&lt;div class=\"system_error\"&gt;Error Occurred - "+ev.data+"&lt;/div&gt;");}; websocket.onclose = function(ev){$('#message_box').append("&lt;div class=\"system_msg\"&gt;Connection Closed&lt;/div&gt;");}; }); &lt;/script&gt; &lt;div class="chat_wrapper"&gt; &lt;div class="message_box" id="message_box"&gt;&lt;/div&gt; &lt;div class="panel"&gt; &lt;input type="text" name="name" hidden="" id="name" value="&lt;?= fSession::get('user_name')?&gt;" maxlength="10" style="width:20%" /&gt; &lt;input type="text" name="pic" hidden="" id="pic" value="&lt;?= fSession::get('user_photo')?&gt;" maxlength="10" style="width:20%" /&gt; &lt;div class="input-group"&gt; &lt;span class="input-group-addon" id="basic-addon3"&gt;&lt;?= fSession::get('user_name')?&gt;&lt;/span&gt; &lt;input type="text" class="form-control" id="message" aria-describedby="basic-addon3" placeholder="Message" maxlength="80"&gt; &lt;/div&gt; &lt;button class="btn btn-default form-inline" id="send-btn"&gt;Send&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>and the server is as follows</p> <pre><code> &lt;?php $host = 'radiobeacononline.com'; //host $port = '9000'; //port $null = NULL; //null var //Create TCP/IP sream socket $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); //reuseable port socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1); //bind socket to specified host socket_bind($socket, 0, $port); //listen to port socket_listen($socket); //create &amp; add listning socket to the list $clients = array($socket); //start endless loop, so that our script doesn't stop while (true) { //manage multipal connections $changed = $clients; //returns the socket resources in $changed array socket_select($changed, $null, $null, 0, 10); //check for new socket if (in_array($socket, $changed)) { $socket_new = socket_accept($socket); //accpet new socket $clients[] = $socket_new; //add socket to client array $header = socket_read($socket_new, 1024); //read data sent by the socket perform_handshaking($header, $socket_new, $host, $port); //perform websocket handshake socket_getpeername($socket_new, $ip); //get ip address of connected socket //$response = mask(json_encode(array('type'=&gt;'system', 'message'=&gt;'A user has joined connected'))); //prepare json data //send_message($response); //notify all users about new connection $time = time(); $file = fopen('app/engine/storage/writeable/logs/chat.log','a+'); fwrite($file,"system: $ip connected $time "); fclose($file); //make room for new socket $found_socket = array_search($socket, $changed); unset($changed[$found_socket]); } //loop through all connected sockets foreach ($changed as $changed_socket) { //check for any incomming data while(socket_recv($changed_socket, $buf, 1024, 0) &gt;= 1) { $received_text = unmask($buf); //unmask data $tst_msg = json_decode($received_text); //json decode // if($tst_msg-&gt;type == message) // { // what it says below // elseif($tst_msg-&gt;type == system) // { // do a system update this will be if the user is online or not. // this will need a lot fo work on it to make sure that they are. // } // elseif($tst_msg-&gt;type == users) // { // update user list. // } // elseif($tst_msg-&gt;type == ping) // { // do ping stuff. // } // elseif($tst_msg-&gt;type == pong) // { // do pong stuff // } $user_name = $tst_msg-&gt;name; //sender name $user_message = $tst_msg-&gt;message; //message text $user_color = $tst_msg-&gt;color; //color $user_pic = $tst_msg-&gt;pic; //color $time = time(); //prepare data to be sent to client $response_text = mask(json_encode(array('type'=&gt;'usermsg', 'name'=&gt;$user_name, 'message'=&gt;$user_message, 'color'=&gt;$user_color, 'pic'=&gt;$user_pic))); send_message($response_text); //send data $file = fopen('app/engine/storage/writeable/logs/chat.log','a+'); fwrite($file,"usermsg $user_name : $user_message $time "); fclose($file); break 2; //exist this loop } $buf = @socket_read($changed_socket, 1024, PHP_NORMAL_READ); if ($buf === false) { // check disconnected client // remove client for $clients array $found_socket = array_search($changed_socket, $clients); socket_getpeername($changed_socket, $ip); unset($clients[$found_socket]); $time = time(); //notify all users about disconnected connection $response = mask(json_encode(array('type'=&gt;'system', 'message'=&gt;$ip.' disconnected'))); send_message($response); $file = fopen('app/engine/storage/writeable/logs/chat.log','a+'); fwrite($file,"system $ip disconected $time "); fclose($file); } } } // close the listening socket socket_close($socket); function send_message($msg) { global $clients; foreach($clients as $changed_socket) { @socket_write($changed_socket,$msg,strlen($msg)); } return true; } //Unmask incoming framed message function unmask($text) { $length = ord($text[1]) &amp; 127; if($length == 126) { $masks = substr($text, 4, 4); $data = substr($text, 8); } elseif($length == 127) { $masks = substr($text, 10, 4); $data = substr($text, 14); } else { $masks = substr($text, 2, 4); $data = substr($text, 6); } $text = ""; for ($i = 0; $i &lt; strlen($data); ++$i) { $text .= $data[$i] ^ $masks[$i%4]; } return $text; } //Encode message for transfer to client. function mask($text) { $b1 = 0x80 | (0x1 &amp; 0x0f); $length = strlen($text); if($length &lt;= 125) $header = pack('CC', $b1, $length); elseif($length &gt; 125 &amp;&amp; $length &lt; 65536) $header = pack('CCn', $b1, 126, $length); elseif($length &gt;= 65536) $header = pack('CCNN', $b1, 127, $length); return $header.$text; } //handshake new client. function perform_handshaking($receved_header,$client_conn, $host, $port) { $headers = array(); $lines = preg_split("/ /", $receved_header); foreach($lines as $line) { $line = chop($line); if(preg_match('/\A(\S+): (.*)\z/', $line, $matches)) { $headers[$matches[1]] = $matches[2]; } } $secKey = $headers['Sec-WebSocket-Key']; $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'))); //hand shaking header $upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake " . "Upgrade: websocket " . "Connection: Upgrade " . "WebSocket-Origin: $host " . "WebSocket-Location: wss://$host:$port/demo/shout.php ". "Sec-WebSocket-Accept:$secAccept "; socket_write($client_conn,$upgrade,strlen($upgrade)); } </code></pre> <p>this works fine in http but does not work in https is there anybody out there that can help with this and make it work on a https system with out having to click something that will allow it after saying unsafe on it?</p> </div>

关于websocket ssl认证

服务器APP之间用websocket通信,未加ssl时正常,服务器加了认证后,客户端URL改成wss:xxx:8443连接不上,求大婶指点

Websocket在刷新时无法连接

<div class="post-text" itemprop="text"> <p>I have got a Websocket server using Ratchet/PHP:</p> <pre><code>&lt;?php require __DIR__.'/../vendor/autoload.php'; use Ratchet\Server\IoServer; use Ratchet\Http\HttpServer; use Ratchet\WebSocket\WsServer; use MyApp\Mediator; $server = IoServer::factory( new HttpServer( new WsServer( new Mediator() ) ), 9000 ); $server-&gt;run(); ?&gt; </code></pre> <p>Mediator class:</p> <pre><code>&lt;?php namespace MyApp; use Ratchet\MessageComponentInterface; use Ratchet\ConnectionInterface; class Mediator implements MessageComponentInterface { protected $clients = []; public function onOpen(ConnectionInterface $conn) { $this-&gt;clients[$conn-&gt;resourceId] = $conn; echo "New connection! ({$conn-&gt;resourceId}) "; } public function onMessage(ConnectionInterface $from, $msg) { echo "Incoming: $msg "; } public function onClose(ConnectionInterface $conn) { unset($this-&gt;clients[$conn-&gt;resourceId]); echo "Connection {$conn-&gt;resourceId} has disconnected "; } public function onError(ConnectionInterface $conn, \Exception $e) { echo "An error has occurred: {$e-&gt;getMessage()} "; $conn-&gt;close(); } } ?&gt; </code></pre> <p>Now on the client side, I have this basic JS code:</p> <pre><code>let ws = new WebSocket('wss://localhost:8443'); ws.addEventListener('open', () =&gt; { ws.send('Hello!'); }); ws.addEventListener('message', event =&gt; { alert(event.data); }); </code></pre> <p>It does work (I can send and receive messages), however here's the problem:</p> <p>When visiting the page for the first time, a connection with the websocket server is established and works fine. When I close the page, the connection is closed (as it should). However, when I refresh the page the connection is closed (on unloading the page, this is normal) but when the page is loaded again, no connection is made to the websocket server. I have to refresh <em>again</em> to make the script connect. This should not happen, right? I have no idea why this is happening, what's causing this. </p> </div>

来自客户端的简单Websocket连接示例

<div class="post-text" itemprop="text"> <p>I would like to rewrite this JavaScript (run in Node) into Go.</p> <pre><code>let io = require('socket.io-client'); let socket = io('http://botws.generals.io'); socket.on('connect', function() { console.log('Connected to server.'); }); </code></pre> <p>(<em>I've tried <a href="https://github.com/graarh/golang-socketio" rel="nofollow noreferrer">this library</a> unsuccessfully; I can elaborate on my noob attempts if that helps</em>)</p> </div>

安卓微信浏览器连接不上websocket,使用其他浏览器正常

安卓微信浏览器连接不上websocket,使用其他浏览器正常 创建方式 var ws ; if('WebSocket' in window) { ws = new WebSocket(url); } else if ('MozWebSocket' in window) { ws = new MozWebSocket(url); } 看到网上说微信上用 wx.connectSocket({ url:"test.php" }); wx.onSocketOpen(function(res){ console.log("WebSocket连接已打开!") }) 不知道这个wx是什么东西,怎么创建的

vue-websocket使用方法?

vue-websocket在vue+webpack搭建的项目里如何使用?求大神解决一下

关于使用autobahn实现websocket开发出现的问题

为了在android上实现websocket,我才用了autobahn这个第三方库函数,其中在使用ws的时候完全没有问题,但是实现wss总是出现如下的错误,这是什么原因呢?![图片说明](https://img-ask.csdn.net/upload/201603/09/1457503980_476370.png) 其中由于我是用的是自签名的证书,我将autobahn中的WebSocketConnection里面进行了如下修改:![图片说明](https://img-ask.csdn.net/upload/201603/09/1457504108_909722.png)

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

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

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

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

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

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

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

和黑客斗争的 6 天!

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

Intellij IDEA 实用插件安利

1. 前言从2020 年 JVM 生态报告解读 可以看出Intellij IDEA 目前已经稳坐 Java IDE 头把交椅。而且统计得出付费用户已经超过了八成(国外统计)。IDEA 的...

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

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

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

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

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

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

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

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

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

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

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

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

魂迁光刻,梦绕芯片,中芯国际终获ASML大型光刻机

据羊城晚报报道,近日中芯国际从荷兰进口的一台大型光刻机,顺利通过深圳出口加工区场站两道闸口进入厂区,中芯国际发表公告称该光刻机并非此前盛传的EUV光刻机,主要用于企业复工复产后的生产线扩容。 我们知道EUV主要用于7nm及以下制程的芯片制造,光刻机作为集成电路制造中最关键的设备,对芯片制作工艺有着决定性的影响,被誉为“超精密制造技术皇冠上的明珠”,根据之前中芯国际的公报,目...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

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

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

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

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

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

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

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

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

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

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

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

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

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

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

Python爬虫,高清美图我全都要(彼岸桌面壁纸)

爬取彼岸桌面网站较为简单,用到了requests、lxml、Beautiful Soup4

差点跪了...

最近微信又搞出了一个大利器,甚至都上了热搜,当然消息最敏捷的自媒体人,纷纷都开通了自己的视频号。01 视频号是什么呢?视频号是微信体系内的短视频,它不同...

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

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

Vue回炉重造之router路由(更新中)

你好,我是Vam的金豆之路,可以叫我豆哥。2019年年度博客之星、技术领域博客专家。主要领域:前端开发。我的微信是 maomin9761,有什么疑问可以加我哦,自己创建了一个微信技术交流群,可以加我邀请你一起交流学习。最后自己也创建了一个微信公众号,里面的文章是我自己精挑细选的文章,主要介绍各种IT新技术。欢迎关注哦,微信搜索:臻美IT,等你来。 欢迎阅读本博文,本博文主要讲述【】,文字通...

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

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

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

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

Java岗开发3年,公司临时抽查算法,离职后这几题我记一辈子

前几天我们公司做了一件蠢事,非常非常愚蠢的事情。我原以为从学校出来之后,除了找工作有测试外,不会有任何与考试有关的事儿。 但是,天有不测风云,公司技术总监、人事总监两位大佬突然降临到我们事业线,叫上我老大,给我们组织了一场别开生面的“考试”。 那是一个风和日丽的下午,我翘着二郎腿,左手端着一杯卡布奇诺,右手抓着我的罗技鼠标,滚动着轮轴,穿梭在头条热点之间。 “淡黄的长裙~蓬松的头发...

大胆预测下未来5年的Web开发

在2019年的ReactiveConf 上,《Elm in Action》的作者Richard Feldman对未来5年Web开发的发展做了预测,很有意思,分享给大家。如果你有机会从头...

立即提问
相关内容推荐