2016-07-26 137 views
0

嗨,夥計們!WebSocket連接到...失敗:在WebSocket握手期間出錯:意外的響應代碼:200

我想在Chrome瀏覽器和Glassfish 4.1.1服務器之間創建websocket連接。 4天沒有成功。 不幸的是,我得到HTTP 200消息,而不是101

鉻DevTool日誌:

"WebSocket connection to 'ws://DOMAIN_NAME:8080/serverendpointdemo/' failed: 
Error during WebSocket handshake: Unexpected response code: 200" 

客戶端代碼:

var ws = new WebSocket ("ws://" + document.location.host + "/serverendpointdemo/"); 

服務器端代碼:

package com.za.tutorial.websocket; 

import javax.websocket.OnClose; 
import javax.websocket.OnError; 
import javax.websocket.OnMessage; 
import javax.websocket.OnOpen; 
import javax.websocket.server.ServerEndpoint; 

@ServerEndpoint("/home/USER_NAME/glassfish4/glassfish/domains/domain1/applications/serverendpointdemo") 
public class ServerEndpointDemo { 
    @OnOpen 
    public void handleOpen() { 
     System.out.println("Client is now connected..."); 
    } 

    @OnMessage 
    public String handleMessage (String message) { 
     return null; 
    } 

    @OnClose 
    public void handleClose() { 
    } 

    @OnError 
    public void handleError (Throwable t) { 
     t.printStackTrace(); 
    } 
} 

也許在這個問題上需要什麼來幫助我? 請幫忙。

+0

我贏得這樣說: 客戶端的JavaScript代碼: 變種WS =新的WebSocket( 「WS:// DOMAIN_NAME:8080/serverendpointdemo/serverendpointdemo」); 幫助鏈接,如果elseone得到它: [鏈接](http://blog.martinandersson.com/making-a-java-ee-7-websocket-serverendpoint-class-discoverable/) [鏈接] (https://glassfish.java.net/docs/4.0/error-message-reference.pdf) [link](http://download.oracle.com/otn-pub/jcp/websocket-1_0-fr -eval-spec/JavaWebSocketAPI_1.0_Final.pdf?AuthParam = 1469574317_cf28b611d89626ae8c534e5f783409ca) – Rinat

+0

這是Glassfish服務器的一個特性。在GlassFish中,如果將應用程序與contextroot mycontextroot部署在偵聽本地主機端口8080的Web容器中,則可以使用ws:// localhost:8080/mycontextroot/hello訪問WebSocket。全文:[鏈接](http://www.oracle.com/technetwork/articles/java/jsr356-1937161.html) – Rinat

回答

0

服務器端: @ServerEndpoint(值= 「/ WS」) 公共類WebSocketConfig {

private String message = ""; 
private String to = ""; 
private String from = ""; 
private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>()); 

@OnOpen 
public void onOpen(Session session, EndpointConfig econfig) throws IOException {   
    System.out.println("New Web Socket Connection created"); 
    session.getBasicRemote().sendText("onOpen new socket connection");    
} 

@OnClose 
public void onClose(Session session) {  
     sessions.remove(session); 
} 

@OnMessage 
public void onMessage(String message, Session session) throws IOException { 

} 

客戶端:

同時進行連接,你應該指定的contextPath 變種WS =新WebSocket(「ws://」+ document.location.host +「/」+ your-contextPathName +「/ serverendpointdemo /」);

HTTP:WS://主機名:端口/ contextPath中/ serverendpoint HTTPS:WSS://主機名:端口/ contextPath中/ serverendpoint

例如: WS://document.location.host+「/ WebsocketDemo/WS「;

+0

添加一些解釋和答案,這個答案如何幫助OP在修復當前問題 –

相關問題