如何将WebSocket连接到Android Applicaton?

时间:2017-02-28 08:04:04

标签: android websocket

我是Android新手。我想制作一个演示,我可以将手机连接到运行在不同计算机上的服务器。我的后端给了我WebSocket URL。我正在实施然后我能够在我的手机上获取浏览器消息,但我无法向服务器发送消息。我做了什么,它在这里。请指导我

public class MainActivity extends Activity {
private WebSocketClient mWebSocketClient;

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

connectWebSocket();

if (savedInstanceState == null) {
    getFragmentManager().beginTransaction()
            .add(R.id.container, new PlaceholderFragment())
            .commit();
}
}


public static class PlaceholderFragment extends Fragment {

public PlaceholderFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    return rootView;
}
}

private void connectWebSocket() {
URI uri;
try {
    uri = new URI("ws://xx.xxxxx.xxxxx.com:9000");
} 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();
}

public void sendMessage(View view) {
EditText editText = (EditText) findViewById(R.id.message);
mWebSocketClient.send(editText.getText().toString());
editText.setText("");
 }
 }

0 个答案:

没有答案