使用WebSocketClient进行简单聊天应用程序

时间:2017-10-30 20:18:13

标签: java android intellij-idea em-websocket-client

我正在尝试学习如何通过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进程:example.com.chatapp,PID:2682     org.java_websocket.exceptions.WebsocketNotConnectedException     在org.java_websocket.WebSocketImpl.send(WebSocketImpl.java:566)     在org.java_websocket.WebSocketImpl.send(WebSocketImpl.java:543)     在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)     at 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)

0 个答案:

没有答案