使用WebSocet连接到服务器时连接被拒绝

时间:2017-12-24 15:26:35

标签: javascript java android websocket java-websocket

我尝试从我的Android应用程序连接到glassFish-server4.1.1 但是给我错误90000ms后无法连接到/ localhost(端口8080) 我更改服务器上的端口,但给我同样的错误 ......

它仅在netbeans上连接到服务器但是在android上给我faild而在我的代码下面

服务器代码`

 @ServerEndpoint("/echo") 

public class WebSocketClass {

 /**
 * @param session
 * @OnOpen allows us to intercept the creation of a new session.
 * The session class allows us to send data to the user.
 * In the method onOpen, we'll let the user know that the handshake was 
 * successful.
 */


@OnOpen
public void onOpen(Session session){
    System.out.println(session.getId() + " has opened a connection"); 
    try {
        session.getBasicRemote().sendText("Connection Established");
    } catch (IOException ex) {
    }
}

/**
 * When a user sends a message to the server, this method will intercept the message
 * and allow us to react to it. For now the message is read as a String.
 * @param message
 * @param session
 */
@OnMessage
public void onMessage12(String message, Session session){
    System.out.println("Message from " + session.getId() + ": " + message);
    try {
        session.getBasicRemote().sendText(message);
    } catch (IOException ex) {
    }
}

/**
 * The user closes the connection.
 * 
 * Note: you can't send messages to the client from this method
 * @param session
 */
@OnClose
public void onClose(Session session){
    System.out.println("Session " +session.getId()+" has ended");
}}

客户端代码

private void connectWebSocket() {
    URI uri;
    try {
        uri = new URI("ws://localhost:8080/WebApplication1/echo");
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return;
    }

    mWebSocketClient = new WebSocketClient(uri) {
        @Override
        public void onOpen(ServerHandshake serverHandshake) {
            Log.i("Websocket", "Opened");
            mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
        }

        @Override
        public void onMessage(String s) {
            final String message = s;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    TextView textView = (TextView)findViewById(R.id.messages);
                    textView.setText(textView.getText() + "\n" + message);
                }
            });
        }

        @Override
        public void onClose(int i, String s, boolean b) {
            Log.i("Websocket", "Closed " + s);
        }

        @Override
        public void onError(Exception e) {
            Log.i("Websocket", "Error " + e.getMessage());
        }
    };
    mWebSocketClient.connect();
}

我不知道为什么会出现这个错误? 任何人都可以帮助我...

1 个答案:

答案 0 :(得分:0)

也许您应该更改IP以反映客户端上安装glassfish服务器的IP