连接到安卓Java上的服务器WebSocket。

huangapple go评论79阅读模式
英文:

Connecting to server's websocket on android java

问题

以下是你提供的代码的翻译部分:

服务器端 WebSocket 代码:

@ServerEndpoint("/websocket")
public class WebsocketListener {

    @OnOpen
    public void handleConnect(Session session) {
        System.out.println("客户端连接: " + session);
    }

    @OnMessage
    public void handleMessage(Session session, String message) {
        System.out.println(session + " : " + message);
        String[] tokens = message.split(":::");

        if(tokens[0].equals("connect")) {
            WebSocketSessionManager.addSession(tokens[1], session);
        } else if(tokens[0].equals("alert")) {
            WebSocketSessionManager.sendMessage(tokens[1]);
        }
    }

    @OnClose
    public void handleDisconnect(Session session) {
        System.out.println(session + "连接关闭.");
        WebSocketSessionManager.removeSession(session);
    }

    @OnError
    public void handleError(Session session, Throwable throwable) {
        throwable.printStackTrace();
        WebSocketSessionManager.removeSession(session);
    }
}

Android Java 客户端 WebSocket 代码:

package com.example.socketexample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

public class MainActivity extends AppCompatActivity {

    private Button button;
    private WebSocketClient webSocketClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                connectToWebSocket();
            }
        });
    }

    private void connectToWebSocket() {

        Log.i("websocket", "connectToWebSocket() 被调用.");
        URI uri;
        try {
            uri = new URI("ws://10.21.20.24:8080/websocket");
        } catch(Exception e){
            e.printStackTrace();
            return;
        }

        webSocketClient = new WebSocketClient(uri) {
            @Override
            public void onOpen(ServerHandshake handshakedata) {
                Log.i("websocket", "已连接至服务器.");
                webSocketClient.send("connect:::TESTKEY");
                webSocketClient.send("alert:::HI");
            }

            @Override
            public void onMessage(String message) {
                Log.i("websocket", message);
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                Log.i("websocket", "连接已关闭.");
            }

            @Override
            public void onError(Exception ex) {
                Log.i("websocket" , "错误 : " + ex.getMessage());
            }
        };
        webSocketClient.connect();
    }
}

请注意,这里只是翻译了你提供的代码部分,其他内容被省略了。如果你有任何问题,欢迎提问。

英文:

I am struggling to connect to server's websocket on android java.

My main class for websocket on server-side is as below.

@ServerEndpoint("/websocket")
public class WebsocketListener {

    @OnOpen
    public void handleConnect(Session session) {
        System.out.println("Client connect : " + session);
    }

    @OnMessage
    public void handleMessage(Session session, String message) {
        System.out.println(session + " : " + message);
        String[] tokens = message.split(":::");

        if(tokens[0].equals("connect")) {
            WebSocketSessionManager.addSession(tokens[1], session);
        } else if(tokens[0].equals("alert")) {
            WebSocketSessionManager.sendMessage(tokens[1]);
        }
    }

    @OnClose
    public void handleDisconnect(Session session) {
        System.out.println(session + "과의 연결 종료.");
        WebSocketSessionManager.removeSession(session);
    }

    @OnError
    public void handleError(Session session, Throwable throwable) {
        throwable.printStackTrace();
        WebSocketSessionManager.removeSession(session);
    }
}

And below is my android-java code for trying to connect to server's websocket.

package com.example.socketexample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.URI;

public class MainActivity extends AppCompatActivity {

    private Button button;
    private WebSocketClient webSocketClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                connectToWebSocket();
            }
        });
    }

    private void connectToWebSocket() {

        Log.i("websocket", "connectToWebSocket() called.");
        URI uri;
        try {
            uri = new URI("ws://10.21.20.24:8080/websocket");
        } catch(Exception e){
            e.printStackTrace();
            return;
        }

        webSocketClient = new WebSocketClient(uri) {
            @Override
            public void onOpen(ServerHandshake handshakedata) {
                Log.i("websocket", "connected to server.");
                webSocketClient.send("connect:::TESTKEY");
                webSocketClient.send("alert:::HI");
            }

            @Override
            public void onMessage(String message) {
                Log.i("websocket", message);
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                Log.i("websocket", "closed.");
            }

            @Override
            public void onError(Exception ex) {
                Log.i("websocket" , "error : " + ex.getMessage());
            }
        };
        webSocketClient.connect();
    }
}

I saw that websocket uses ws:// protocol, so I set the URI to ws://10.21.20.24, which is the IP address in my wifi.

For server's websocket, I am using the pom.xml dependency below.

<dependency>
        <groupId>javax.websocket</groupId>
        <artifactId>javax.websocket-api</artifactId>
        <version>1.1</version>
        <scope>provided</scope>
</dependency>

For android's websocket, I am using the gradle dependency below.

implementation 'org.java-websocket:Java-WebSocket:1.3.0'

Thank you so much in advance. 连接到安卓Java上的服务器WebSocket。

答案1

得分: 2

对于所有遇到与我相同问题的人...

我通过将 new Draft_17() 添加为 new WebSocketClient() 的第二个参数来解决了这个问题。代码总结如下。

private void connectToWebSocket() {

    Log.i("websocket", "connectToWebSocket() 被调用。");
    URI uri;
    try {
        uri = new URI("ws://10.21.20.24:8080/websocket");
    } catch(Exception e){
        e.printStackTrace();
        return;
    }

    webSocketClient = new WebSocketClient(uri, new Draft_17()) {
        // ...
    }
}

然而,这个问题来自于2017年,我认为我需要为 Draft_17 寻找一个替代方案。

https://github.com/TooTallNate/Java-WebSocket/issues/478

祝好运!

英文:

For everyone who is suffering from the same problem that I encountered...

I solved the problem by adding new Draft_17() as the second parameter of new WebSocketClient(). The code is summarized as below.

private void connectToWebSocket() {

    Log.i("websocket", "connectToWebSocket() called.");
    URI uri;
    try {
        uri = new URI("ws://10.21.20.24:8080/websocket");
    } catch(Exception e){
        e.printStackTrace();
        return;
    }

    webSocketClient = new WebSocketClient(uri, new Draft_17()) {
        // ...
    }
}

However, this issues is from year 2017, and I think I have to find an alternative for Draft_17.

https://github.com/TooTallNate/Java-WebSocket/issues/478

Good luck!

huangapple
  • 本文由 发表于 2020年8月24日 19:50:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63560483.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定