websocket response code: 200 100C

注解方式实现 前端html执行到 var ws = new WebSocket("ws://");的时候 浏览器控制台提示 websocket failed: Error during WebSocket handshake: Unexpected response code: 200

环境 :struts2 spring4 tomcat8 jdk 1.8

说明:单独的web工程可以 加入逻辑到 struts spring 里面 就报错


这个我看过了 , 拦截器我已经排除了,struts.xml 我也加了,还可能是其它地方吗?


Csdn user default icon
spring整合websocket出错,Unexpected response code: 404

1. 下面是代码: public class MarcoHandler extends AbstractWebSocketHandler { @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { System.out.println("Received message:"+message.getPayload()); Thread.sleep(2000); session.sendMessage(new TextMessage("Polo!")); } } websocket的xml配置 <websocket:handlers> <websocket:mapping handler="marcoHandler" path="/marco"/> </websocket:handlers> <bean id="marcoHandler" class="com.camle.entity.MarcoHandler"/> web.xml的配置 ``` <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:websocket.xml</param-value> </context-param> ``` javascript代码 <script type="text/javascript"> var url = 'ws://'+window.location.host+'/mvcAndWebsocket/marco'; var sock = new WebSocket(url); sock.onopen = function(){ console.log('Opening'); sayMarco(); }; sock.onmessage = function(e){ console.log('Received message:',e.data); setTimeout(function(){sayMarco()},2000); }; sock.onclose = function(){ alert(window.location.host); console.log('Closing'); }; function sayMarco(){ console.log('Sending Marco!'); sock.send('Marco!'); } </script>

HTML5 / PHP WebSocket连接失败:WebSocket握手期间出错:意外响应代码:200

<div class="post-text" itemprop="text"> <p>I Think some people Just like to do press "This question does not show any research effort; it is unclear or not useful" Button. I really don't know what are they trying to prove?</p> <p>If you think or believe this question does not make any sense, please do comment first before reach a calculation </p> <p>I am trying to connect to my PHP socket server from the browser. This the error I am getting.</p> <p><strong><em>I did check all different post from stackoverflow, but nothing helped.</em></strong></p> <p>When I am using WS. it is working fine. When I am using WSS it is not working.</p> <p>"WebSocket connection to failed: Error during WebSocket handshake: Unexpected response code: 200"</p> <p>This is my apache Configuration</p> <pre><code>ServerName ProxyRequests off ProxyPass "/ws/" "ws://localhost:9090/ws" ProxyPass "/wss/" "wss://localhost:9090/wss" </code></pre> <p>JS</p> <pre><code>function socketClient(vSocketIdentifications) { console.log("I AM IN"); var $cHost = ""; var $cPort = 9090; // this.wsUri = "wss://" + $cHost +":" + $cPort; /* * ENABLE THIS WHEN IN PRODUCTIONS * */ if (window.location.hostname == $cHost){ this.wsUri = "ws://" + $cHost + ":" + $cPort; } else { this.wsUri = ((window.location.protocol === "https:") ? "wss://" : "ws://") + window.location.hostname + ":" + $cPort; } this.socket = ""; //create a new WebSocket object. this.socket = new WebSocket(this.wsUri); /*Let socket know who you are?*/ var msg = { msgFrom: vSocketIdentifications, msg: "Hi", msgClient: "js" }; this.socket.onopen = () =&gt; this.socket.send(JSON.stringify(msg)); // Send text to all users through the server function sendInitMsgToServer() { // Construct a msg object containing the data the server needs to process the message from the chat client. var msg = { msgFrom: vSocketIdentifications, msg: "Hi" }; // Send the msg object as a JSON-formatted string. this.socket.send(JSON.stringify(msg)); } //#### Message received from server? this.socket.onmessage = function(ev) { var msg = JSON.parse(ev.data); //PHP sends Json data console.log(msg); var type = msg.type; //message type var umsg = msg.message; //message text var uname = msg.name; //user name var ucolor = msg.color; //color if(type == 'usermsg') { //$('#message_box').append("&lt;div&gt;&lt;span class=\"user_name\" style=\"color:#"+ucolor+"\"&gt;"+uname+"&lt;/span&gt; : &lt;span class=\"user_message\"&gt;"+umsg+"&lt;/span&gt;&lt;/div&gt;"); if(umsg!=""){ document.getElementById("information").innerHTML=umsg+"&lt;br/&gt;"; }else{ document.getElementById("progress").style.display="none"; document.getElementById("information").innerHTML="I am done . What Next ? "+"&lt;br/&gt;"; } } }; this.closeSocket = function() { this.socket.close(); }; }; </code></pre> </div>

java websocket报错302

WebSocket connection to 'ws://' failed: Error during WebSocket handshake: Unexpected response code: 302


初学WebSocket,做了一个Demo,出现404错误。 WebSocket connection to 'ws://localhost:8088/chat/begin?uname=xiaoming' failed: Error during WebSocket handshake: Unexpected response code: 404 JS代码: ``` var chat={}; chat.socket=null; var uname="<%=request.getSession().getAttribute("uname")%>" function conn(){ connect("ws://localhost:8088/chat/begin?uname="+uname); } function connect(host){ if("WebSocket" in window){ chat.socket=new WebSocket(host); }else if("MoWebSocket" in window){ chat.socket=new MoWebSocket(host); }else{ console.log("当前浏览器不支持WebSocket"); return; } } ``` 后台终端代码: ``` @ServerEndpoint("/begin") public class ChatServer { @OnOpen public void start(Session session){ System.out.println(session.getQueryString()); } } ``` 使用的是eclipse开发,Web服务器使用Tomcat7,jdk版本是1.8。

javascript 的socket 报出的“200”错误,怎么解决

WebSocket connection to 'ws://' failed: Error during WebSocket handshake: Unexpected response code: 200 握手信息200是错误???不是很懂 以下是出事故的代码: connect : function(url) { // Websocket initialization if (this.ws != undefined) { this.ws.close(); delete this.ws; } this.ws = new WebSocket(url); //<==there is a error O~O this.ws.binaryType = "arraybuffer"; this.ws.onopen = () => { log("Connected to " + url); };

WebSocket连接失败:连接建立错误:net :: ERR_SSL_PROTOCOL_ERROR

<div class="post-text" itemprop="text"> <p>当我试图通过wss://连接到WebSocket时,我为什么会得到这个错误,但是在ws://上却没问题呢?</p> <h1>错误:</h1> <pre><code>WebSocket connection failed: Error in connection establishment: net::ERR_SSL_PROTOCOL_ERROR </code></pre> <h1>代码:</h1> <pre><code>package main import ( "fmt" "log" "net/http" //"encoding/json" "github.com/gorilla/websocket" ) var clients map[*websocket.Conn]*Client var upgrader = websocket.Upgrader{ CheckOrigin : func(r *http.Request) bool{ return true }, } type Client struct{ session_id string block_id uint module string } func main(){ var port uint = 8000 http.HandleFunc("/", handleConnections) log.Printf("Websocket server started on: %d", port) err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil) if err != nil { log.Fatal("ListenAndServe: ", err) } } func handleConnections(w http.ResponseWriter, r *http.Request){ // Upgrade initial GET request to a websocket ws, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Print(err) return } defer ws.Close() log.Print("Connection established to IP: ", r.RemoteAddr) ... } </code></pre> </div>

与“ws:// localhost:8080 /”的WebSocket连接失败:这个报错是怎么回事?

我的客户端脚本和服务器之间没有WebSocket连接,它在我当前的环境中运行得很好。同时,我也遵循这个<a href="http://socketo.me/docs/push" rel="nofollow noreferrer">链接</a>。 下面是一个服务器脚本,它初始化WebSocket服务器并让客户端连接到了8080端口。</p> <pre><code>public function run() { $loop = Factory::create(); $pusher = new Pusher; $context = new Context($loop); $pull = $context-&gt;getSocket(ZMQ::SOCKET_PULL); $pull-&gt;bind('tcp://'); // Binding to means the only client that can connect is itself $pull-&gt;on('message', array($pusher, 'onBlogEntry')); // Set up our WebSocket server for clients wanting real-time updates $webSock = new Server('', $loop); // Binding to means remotes can connect $webServer = new IoServer( new HttpServer( new WsServer( new WampServer( $pusher ) ) ), $webSock ); $loop-&gt;run(); </code></pre> <p>这是客户端脚本:</p> <pre><code>var conn = new ab.Session('ws://localhost:8080', function() { /* subscribe to following topics */ conn.subscribe('new_order', function(topic, data) .. </code></pre> <p>同样,这在本地设置中运行良好。</p> <p>还要注意的是,我的应用程序是使用来自docker容器的指定端口承载的。</p> <pre><code> </code></pre> <p>我还尝试在客户端脚本中指定IP:</p> <pre><code>var conn = new ab.Session('ws://', function() { /* subscribe to following topics */ conn.subscribe('new_order', function(topic, data) ... </code></pre> <p>在这种情况下,我会得到以下错误:</p> <pre><code>WebSocket connection to 'ws://' failed: Error during WebSocket handshake: Unexpected response code: 403 </code></pre> <p>这里缺少什么?</p> </div>


今天下午照着网上的案例弄了一个websocket的入门demo。但是自己照着打了一份后一直报404。 WebSocket connection to 'ws://' failed: Error during WebSocket handshake: Unexpected response code: 404 因为是最简单的demo。没有拦截器什么的。该配的注解还有方法都有写了。

websocket-建立连接错误:net :: ERR_INSECURE_RESPONSE

<div class="post-text" itemprop="text"> <p>Can't connect to websocket server..</p> <p>I use the exact same <code>private.key</code> and <code>public.crt</code> that I use with <code>nginx</code> </p> <p>The cert is self-signed but works fine with the rest of the website over HTTPS via nginx</p> <p>The websocket server works when using <code>ws://</code> when the line with <code>http.ListenAndServe()</code> is uncommented</p> <pre><code>package main import ( "flag" "fmt" "log" "net/http" ) const PORT uint = 8000 func main(){ host := parse_flags() hub := newHub() go hub.run() http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { serve(hub, w, r) }) server_host := fmt.Sprintf("%s:%d", host, PORT) log.Println("Server listening on:", server_host) err := http.ListenAndServeTLS(server_host, fmt.Sprintf("/var/ini/ssl/%s/public.crt", host), fmt.Sprintf("/var/ini/ssl/%s/private.key", host), nil) //err := http.ListenAndServe(server_host, nil) if err != nil { log.Fatal("ListenAndServe:", err) } } </code></pre> </div>


<div class="post-text" itemprop="text"> <p>I’m trying to initiate a websocket connection between chrome browser client and server.</p> <p>Overview of my implementation : There are set of different up and running projects. The load balancer to all other projects and it handle all http requests, routes and proxy to other sub projects. These all projects use load balancers. My attempt is to create a websocket connection from chrom browser to one sub project.</p> <blockquote> <p>caddy version : 0.9.3</p> <p>websocket go library : github.com/gorilla/websocket 1</p> </blockquote> <pre><code>// Starting caddy server to server static files args := []string{"bin/caddy", "--conf=" + commons.ServerConfigurations.CaddyFile, "-pidfile=bin/caddy.pid"} if err := exec.Command("nohup", args...).Start(); err != nil { log.Fatalln("Error occourred while starting caddy server : ", err.Error()) os.Exit(1) } //Starting the API server router := routes.NewRouter() http.Handle("/", router) httpsServer := &amp;http.Server{ Addr: ":" + strconv.Itoa(commons.ServerConfigurations.HttpsPort+ commons.ServerConfigurations.PortOffset), Handler: logHandler, ReadTimeout: time.Duration(commons.ServerConfigurations.ReadTimeOut) * time.Second, WriteTimeout: time.Duration(commons.ServerConfigurations.WriteTimeOut) * time.Second, MaxHeaderBytes: 1 &lt;&lt; 20, } httpsServer.ListenAndServeTLS(commons.ServerConfigurations.SSLCertificateFile, commons.ServerConfigurations.SSLKeyFile) </code></pre> <p>First when client reach to the domain, $DOMAIN_NAME such as www.sample.com. Caddy proxy the client request to the <a href="https://localhost:8107/analytics" rel="nofollow noreferrer">https://localhost:8107/analytics</a> </p> <pre><code>https://{$DOMAIN_NAME}/analytics/ { tls pem_file key_file proxy / https://localhost:8105/analytics { websocket insecure_skip_verify } } </code></pre> <p>There are multiple standalone servers. Following is the caddy configuration of server.It serve static files at the directory in <em>webapps/analytics</em></p> <pre><code>localhost:8105/analytics { root webapps/analytics gzip ext .html tls pem_file key_file proxy /api https://localhost:8108 { HTTPS port:8108 websocket insecure_skip_verify } } </code></pre> <p>Inside the analytics sub project, " /api/ws " would trigger CreateSocketConnection() method.</p> <pre><code>//Starting the API server router := routes.NewRouter() http.Handle("/", router) http.HandleFunc("/api/ws", api.CreateSocketConnection) </code></pre> <p>CreateSocketConnection implementation :</p> <pre><code>func CreateSocketConnection(w http.ResponseWriter, r *http.Request) { var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } _, err = upgrader.Upgrade(w, r, nil) if err != nil { log.Fatal("upgrader failed :", err.Error()) } //controllers.HandleSocket(ws) } </code></pre> <p>Client side implementation :</p> <pre><code>conn = new WebSocket("wss://xxxx.com/analytics/api/ws"); </code></pre> <p>Websocket upgrade error happen in golang backend server</p> <blockquote> <p>2018/06/21 16:53:41 http: TLS handshake error from remote error: tls: bad certificate</p> </blockquote> <p>How I use this secure https and websocket in same web server.Is it posible ?</p> <blockquote> <p>web request : 'wss://xxxx.com/analytics/api/ws' failed: Error during WebSocket handshake: Unexpected response code: 502</p> </blockquote> <p>Am I missing something in my implementation?</p> <p>Thanks in advance</p> </div>

.net websocket 实现 报错

Error during WebSocket handshake: Unexpected response code: 200 chrome控制台报的错误 action代码 ``` public HttpResponseMessage T() { if (System.Web.HttpContext.Current.IsWebSocketRequest) { System.Web.HttpContext.Current.AcceptWebSocketRequest(ProcessWSChat); } return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols); //return View(); } private async Task ProcessWSChat(AspNetWebSocketContext context) { System.Net.WebSockets.WebSocket socket = context.WebSocket; while (true) { //ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]); //WebSocketReceiveResult result = await socket.ReceiveAsync( // buffer, CancellationToken.None); if (socket.State == WebSocketState.Open) { //string userMessage = Encoding.UTF8.GetString( // buffer.Array, 0, result.Count); string userMessage = DateTime.Now.ToString(); ArraySegment<byte> buffer = new ArraySegment<byte>( Encoding.UTF8.GetBytes(userMessage)); await socket.SendAsync( buffer, WebSocketMessageType.Text, true, CancellationToken.None); } else { break; } } } ``` js代码 ``` <script type="text/javascript"> var serverData,statusDiv,ws; //var SERVER_URL = "/Dou/T"; window.onload = function () { ws = new WebSocket("ws://" + window.location.host + "/Sun/T"); serverData = document.getElementById("serverData"); statusDiv = document.getElementById("statusDiv"); startlistenServer(); } function startlistenServer() { statusDiv.innerHTML="Start Connect Server..."; //var es = new EventSource(SERVER_URL); ws.onopen = openHandler; ws.onerror = errorHandler; ws.onmessage = messageHandler; } function openHandler(e) { statusDiv.innerHTML = "Server Open<br>"; } function errorHandler(e) { statusDiv.innerHTML = "Error<br>"+e.message; } function messageHandler(e) { serverData.innerHTML = e.data; } </script> ```


jmeter压测websocket,查看结果书中请求和相应数据中没有东西,取样器结果中: Response message: [Execution Flow] - Opening new connection - Using response message pattern "" - Using disconnect pattern "" - Waiting for the server connection for 5000 MILLISECONDS - Cannot connect to the remote server - Waiting for messages for 20000 MILLISECONDS - WebSocket session wasn't started (...that's odd) - WebSocket client closed by the client [Variables] - Message count: 0 [Problems] Response headers: SampleResult fields: ContentType: DataEncoding: UTF-8

django websocket 聊天功能 用nginx代理 访问失败

django 项目 用dwebsocket 实现简单的聊天功能 本地调试已经成功 发布到服务器用nginx做代理, 链接失败 firefox 报错信息: ``` Firefox 无法建立到 ws://xxxxxx/ 服务器的连接。 ``` chrome 报错信息: ``` WebSocket connection to 'ws://xxxxxxx/' failed: Error during WebSocket handshake: Unexpected response code: 400 ``` nginx 配置如下: ``` server { server_name xxxxxxxxxxxxx; listen 80; location /static { root /var/fixpdq; } location /media { root /var/fixpdq; } location / { proxy_pass; proxy_set_header Host $host; proxy_http_version 1.1; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Upgrade $http_upgrade; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Connection "upgrade"; } } ``` django view 代码如下(多余代码省略了) ``` @require_websocket def chat(request): if request.is_websocket(): print('握手成功') .... ``` 本地调试用127.0.0.1 访问是没问题的, 但在本机用局域网ip访问, 就不通, 发布到服务器, 用nginx做代理, 也是不通, 确定的是前端请求已经到达后台代码了. 我想可能是nginx配置的问题 或者是请求到达服务器nginx之前已然就不是socket请求了(因为本机用局域网ip访问也不通), 但是试过很多方法了, 在view 里request.is_websocket() 这句代码是false, nginx转发后居然不是socket请求了, 那肯定就是nginx的配置问题了, 不应该是django 的问题, 求大神帮帮忙!!!

springmvc 整合websocket 报错 404

第一: pom 配置文件: <dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> <version>1.0</version> <scope>provided</scope><!--这个是从网上看的是为了解决jar包冲突的 --> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> <version>4.1.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-messaging</artifactId> <version>4.1.6.RELEASE</version> </dependency> 第二步: 【注册,启动 websocket server 和 握手拦截器 】 @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { System.out.println("....注册......"); registry.addHandler(myhandler(), "/websocket").addInterceptors(myInterceptors()).setAllowedOrigins("*"); registry.addHandler(myhandler(), "/sockjs/websocket").addInterceptors(myInterceptors()).withSockJS(); } @Bean public WebSocketHandler myhandler() { System.out.println("....服务端......"); return new WebsocketEndPoint(); } @Bean public HandshakeInterceptor myInterceptors() { System.out.println("....握手拦截器......"); return new HandshakeInterceptor(); } } public class WebsocketEndPoint extends TextWebSocketHandler { private Logger logger = LoggerFactory.getLogger(WebsocketEndPoint.class); @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { super.handleTextMessage(session, message); logger.debug("GOMA === > WebSocketEndPoint.handlerTextMessage..."); TextMessage returnMessage = new TextMessage(message.getPayload()+" received at server"); session.sendMessage(returnMessage); } } public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor { private Logger logger = Logger.getLogger(getClass()); @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { logger.debug("GOMA ===> Before Handshake"); return super.beforeHandshake(request, response, wsHandler, attributes); } @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) { logger.debug("GOMA ===> After Handshake"); super.afterHandshake(request, response, wsHandler, ex); } } 第三步:页面 client 我的tomcat 的端口是 9018 socket = new WebSocket('ws://localhost:9018/testSocket/websocket'); 运行报错: WebSocket connection to 'ws://localhost:9018/testSocket/websocket' failed: Error during WebSocket handshake: Unexpected response code: 400 这是为啥? 都配置了 ,为啥 是404 奇怪~~~ 那个大神给我解决一下

连接到在AWS Beanstalk上运行的GO Websocket服务器

<div class="post-text" itemprop="text"> <p>I have a websocket server built with go running on AWS beanstalk. I'm running a load balancer with a SSL cert. I'm having issues connecting to it via the browser. If I try to connect to it through another go program running on my terminal everything works fine. I've updated my environment to accept <code>TCP</code> instead of <code>HTTP</code> connections on port <code>80</code>.</p> <p>When I try to connect from the webapp though I get this error.</p> <pre><code>WebSocket connection to 'wss://root.com/users/fcbd7f8d-2ef6-4fe2-b46c-22db9b107214/sockets/client' failed: Error during WebSocket handshake: Unexpected response code: 400 </code></pre> <p>When I check the AWS logs I find this error.</p> <pre><code>the client is not using the websocket protocol: 'websocket' token not found in 'Upgrade' header </code></pre> <p><strong>UPDATE</strong></p> <p>if I run the webapp on my localhost and change the connection string from <code>wss://</code> to <code>ws://</code> it works. If I try the same url in the live webapp I get an ssl error.</p> <pre><code>Mixed Content: The page at 'https://root.com/captions' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://root.com/users/fcbd7f8d-2ef6-4fe2-b46c-22db9b107214/sockets/client'. This request has been blocked; this endpoint must be available over WSS. </code></pre> </div>


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

Javascript websocket不会连接到php websocket

<div class="post-text" itemprop="text"> <p>So I've been trying to get this whole connection between <em>PHP</em> socket server and <em>Javascript</em> websockets working, but I cant get them to connect. I have looked everywhere to figure out what I'm doing wrong. My guess is it's the protocol but I have no idea. Everything helps, comment if you have questions.</p> <p><strong>Client-Side Example</strong></p> <pre><code>&lt;script&gt; var connection = new WebSocket('ws://'); connection.onopen = function () { connection.send('Ping'); // Send the message 'Ping' to the server }; // Log errors connection.onerror = function (error){ console.log('WebSocket Error ' + error); }; // Log messages from the server connection.onmessage = function (e) { console.log('Server: ' + e.data); }; &lt;/script&gt; </code></pre> <p><strong>Server-Side Example -PHP</strong></p> <pre><code>&lt;?php $conn = stream_socket_server('tcp://'); while ($socket = stream_socket_accept($conn)) { $pkt = stream_socket_recvfrom($socket, 1500, 0, $peer); if (false === empty($pkt)) { stream_socket_sendto($socket, $pkt, 0, $peer); } fclose($socket); usleep(10000); //100ms delay } stream_socket_shutdown($conn, \STREAM_SHUT_RDWR); ?&gt; </code></pre> <p><strong>Console Log Error</strong></p> <pre><code>VM4666:35 WebSocket connection to 'ws://' failed: Error during WebSocket handshake: net::ERR_INVALID_HTTP_RESPONSE </code></pre> <p>I understand that there are many questions on here similar but I cant seem to find a solution, I appreciate any help!</p> </div>


<div class="post-text" itemprop="text"> <p>Fairly new gopher here. Limited experience.</p> <p>I am going through a book that explores websockets and I hit a dead end. I have assembled a simple chat app with the examples from the book and when I run it I hit the following error:</p> <blockquote> <p>WebSocket connection to 'ws://localhost:5000/room' failed: Error during WebSocket handshake: Unexpected response code: 200</p> </blockquote> <p>Does anybody know what causes this?</p> <p>main.go</p> <pre><code>package main import ( "html/template" "log" "net/http" "path/filepath" "sync" ) type templateHandler struct { //once is an object that will perform exactly one action once sync.Once filename string templ *template.Template } func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { //this function call will be executed only once t.once.Do(func() { t.templ = template.Must(template.ParseFiles(filepath.Join("templates", t.filename))) log.Println("one time") }) t.templ.Execute(w, nil) } func main() { http.Handle("/", &amp;templateHandler{filename: "chat.html"}) if err := http.ListenAndServe(":5000", nil); err != nil { log.Fatal("ListenAndServe", err) } } </code></pre> <p>client.go</p> <pre><code>package main //Notes on channels //read from channel x to a //a := &lt;- x //write 5 to channel x //x &lt;- 5 import ( "github.com/gorilla/websocket" ) //client represents a single chatting user. type client struct { //client represents a single chatting user socket *websocket.Conn //sent is a channel on which messages are sent send chan []byte //room is the room this client is chatting in room *room } func (c *client) read() { for { //if err is nil after the execution of ReadMessage() //execute the line between the braces if _, msg, err := c.socket.ReadMessage(); err == nil { c.room.forward &lt;- msg } else { break } } c.socket.Close() } func (c *client) write() { for msg := range c.send { if err := c.socket.WriteMessage(websocket.TextMessage, msg); err != nil { break } } c.socket.Close() } </code></pre> <p>room.go</p> <pre><code>package main import ( "log" "net/http" "github.com/gorilla/websocket" ) type room struct { //forward is a channel that holds incoming messages //that should be forwarded to other clients forward chan []byte //join is a channel for clients wishing to join the room join chan *client //leave is a channel for clients wishing to leave the room. leave chan *client //clients holds al the current clients in this room. clients map[*client]bool } func (r *room) run() { for { select { case client := &lt;-r.join: //joining r.clients[client] = true case client := &lt;-r.leave: //leaving delete(r.clients, client) close(client.send) case msg := &lt;-r.forward: //forward message to all clients for client := range r.clients { select { case client.send &lt;- msg: default: //failed to send delete(r.clients, client) close(client.send) } } } } } const ( socketBufferSize = 1024 messageBufferSize = 256 ) //in order for the browser to switch to the websocket //protocol a header with an upgrade request from http //to websocket must be sent var upgrader = &amp;websocket.Upgrader{ ReadBufferSize: socketBufferSize, WriteBufferSize: socketBufferSize, } func (r *room) ServeHTTP(w http.ResponseWriter, req *http.Request) { socket, err := upgrader.Upgrade(w, req, nil) if err != nil { log.Fatal("ServeHTTP:", err) return } client := &amp;client{ socket: socket, send: make(chan []byte, messageBufferSize), room: r, } r.join &lt;- client defer func() { r.leave &lt;- client }() go client.write() client.read() } </code></pre> <p>chat.html</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Chat&lt;/title&gt; &lt;style&gt; input {display:block;} ul{list-style:none;} &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;ul id="messages"&gt;&lt;/ul&gt; &lt;form id="chatbox"&gt; &lt;textarea&gt;&lt;/textarea&gt; &lt;input type="submit" value="Send" /&gt; &lt;/form&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt; &lt;/script&gt; &lt;script&gt; $(function(){ var socket = null; var msgBox = $("#chatbox textarea"); var messages = $("#messages"); $("#chatbox").submit(function(){ if (!msgBox.val()) return false; if (!socket) { alert("Error: There is no socket connection."); return false; } socket.send(msgBox.val()); msgBox.val(""); return false; }); if (!window["WebSocket"]) { alert("Error: Your browser does not support web sockets.") }else { socket = new WebSocket("ws://localhost:5000/room"); socket.onclose = function() { alert("Connection has been closed."); } socket.onmessage = function(e) { messages.append($("&lt;li&gt;").text(e.data)); } } }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> </div>

在AWS Application Load Balancer上使用Go时,WebSocket连接失败并显示301

<div class="post-text" itemprop="text"> <p>I'm trying to run a Go Server with WebSockets on an AWS Application Load Balancer but I am getting an <strong>'Error during WebSocket handshake: Unexpected response code: 301'</strong>. </p> <p>AWS says that The Application Load Balancers supports WebSockets via <strong>ws://</strong> protocols but I can not find any further documentation other than the following:</p> <p>Here's <a href="https://aws.amazon.com/blogs/aws/new-aws-application-load-balancer/" rel="nofollow noreferrer">aws load-balancer link</a></p> <blockquote> <p>The Application Load Balancer supports two additional protocols: WebSocket and HTTP/2.</p> <p>WebSocket allows you to set up long-standing TCP connections between your client and your server. This is a more efficient alternative to the old-school method which involved HTTP connections that were held open with a “heartbeat” for very long periods of time. WebSocket is great for mobile devices and can be used to deliver stock quotes, sports scores, and other dynamic data while minimizing power consumption. ALB provides native support for WebSocket via the ws:// and wss:// protocols.</p> </blockquote> <p>I can get JavaScript to connect to my Go server via WebSockets locally but when I deploy AWS it does not work. This is when the JavaScript displays a 301 error.</p> <p>The Application Load Balancer is listening on <strong>HTTP: 80</strong> and that traffic is being directed to <strong>HTTPS: 443</strong>. All of the Security Groups are pretty much similarly set up to allow traffic through. If I do a normal GET call to retrieve data from my server while deployed on AWS it works perfectly fine.</p> <p>Local call that works to connect to localhost</p> <pre><code>&lt;script&gt; let socket = new WebSocket("ws://localhost:8080/websocket") console.log("Attempting Websocket Connection") socket.onopen = () =&gt; { console.log("Successfully Connected"); socket.send("Hi From the Client!") } socket.onclose = (event) =&gt; { console.log("Socket Closed Connection: ", event) } socket.onmessage = (msg) =&gt; { console.log(msg); } socket.onerror = (error) =&gt; { console.log("Socket Error: ", error) } &lt;/script&gt; </code></pre> <p>Connect to remote server that does not work.</p> <pre><code>&lt;script&gt; let socket = new WebSocket("ws://myexamplesite.com/websocket") console.log("Attempting Websocket Connection") socket.onopen = () =&gt; { console.log("Successfully Connected"); socket.send("Hi From the Client!") } socket.onclose = (event) =&gt; { console.log("Socket Closed Connection: ", event) } socket.onmessage = (msg) =&gt; { console.log(msg); } socket.onerror = (error) =&gt; { console.log("Socket Error: ", error) } &lt;/script&gt; </code></pre> <p>nginx.conf </p> <pre><code>events { worker_connections 1024; } http { server_tokens off; server { listen 80; location / { proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $http_host; proxy_pass http://web:8080/; } } } </code></pre> <p>I expect to be able to establish a WebSocket connection but the following error is returning from the JavaScript file: </p> <p><em>WebSocket connection to 'ws://myexamplesite.com/websocket' failed: Error during WebSocket handshake: Unexpected response code: 301</em></p> </div>


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




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

和黑客斗争的 6 天!

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

Intellij IDEA 实用插件安利

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



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



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






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


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


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

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

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


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


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




本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...




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


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




编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

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





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

《Oracle Java SE编程自学与面试指南》最佳学习路线图2020年最新版(进大厂必备)







内容导航: 1、TIOBE排行榜 2、总榜(2020年6月份) 3、本月前三名 3.1、C 3.2、Java 3.3、Python 4、学习路线图 5、参考地址 1、TIOBE排行榜 TIOBE排行榜是根据全世界互联网上有经验的程序员、课程和第三方厂商的数量,并使用搜索引擎(如Google、Bing、Yahoo!)以及Wikipedia、Amazon、YouTube统计出排名数据。