0

我正在尝试学习如何通过 android 中的 websocket 建立连接。我正在尝试使用 websocket 客户端向服务器发送消息,然后尝试在屏幕上查看它。

我可以启动应用程序,但是当我键入消息然后单击发送按钮时,我收到以下错误:org.java_websocket.exceptions.WebsocketNotConnectedException

这是我的 MainActivity 类:

public class MainActivity extends AppCompatActivity {

private TextView userView;
private ListView listView;
private EditText textToSend;
private Button sendButton;

private WebClient webClient;
private JSONObject jsonObject;

private URI uri;

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

    userView = (TextView) findViewById(R.id.userView);
    listView = (ListView) findViewById(R.id.listView);
    textToSend = (EditText) findViewById(R.id.textToSend);
    sendButton = (Button) findViewById(R.id.sendButton);

    try {
        uri = new URI("http://127.0.0.1:8080/chat");
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    webClient = new WebClient(uri);
    webClient.connect();

    sendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            jsonObject = new JSONObject();
            try {
                jsonObject.put("message",textToSend.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }

            webClient.send(jsonObject.toString());


        }
    });
}
}

这是 WebClient 类:

公共类 WebClient 扩展 WebSocketClient {

public WebClient(URI serverURI) {
    super(serverURI);
}

@Override
public void onOpen(ServerHandshake handshakedata) {

    Log.e("Websocket", "Opened");

}

@Override
public void onMessage(String message) {



}

@Override
public void onClose(int code, String reason, boolean remote) {

}

@Override
public void onError(Exception ex) {

}
}

这是单击发送按钮后的 logcat:

--------- 崩溃开始 10-30 20:09:50.830 2682-2682/example.com.chatapp E/AndroidRuntime: FATAL EXCEPTION: main Process: example.com.chatapp, PID: 2682 org. java_websocket.exceptions.WebsocketNotConnectedException at org.java_websocket.WebSocketImpl.send(WebSocketImpl.java:566) at org.java_websocket.WebSocketImpl.send(WebSocketImpl.java:543) at org.java_websocket.client.WebSocketClient.send(WebSocketClient.java: 171) 在 ziad.example.com.chatapp.MainActivity$1.onClick(MainActivity.java:60) 在 android.view.View.performClick(View.java:5637) 在 android.view.View$PerformClick.run(View. java:22429) 在 android.os.Handler.handleCallback(Handler.java:751) 在 android.os.Handler.dispatchMessage(Handler.java:95) 在 android.os.Looper.loop(Looper.java:154) 在android.app.ActivityThread.main(ActivityThread.java:6119) 在 java.lang.reflect.Method.invoke(Native Method) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 在 com.android.internal.os.ZygoteInit.main( ZygoteInit.java:776)

4

0 回答 0