Android中okhttp实现socket通讯
导入依赖
implementation'com.squareup.okhttp3:okhttp:3.8.1'
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="start"
android:textSize="16sp" />
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/start2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="start2"
android:textSize="16sp" />
<TextView
android:id="@+id/text2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
mainActvity:
/**
* okhttp是3.5以后才添加对WebSocket的支持
*/
public class MainActivityextends AppCompatActivity {
private Buttonstart;
private TextViewtext;
private Buttonstart2;
private TextViewtext2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.start);
text = (TextView) findViewById(R.id.text);
start2 = (Button) findViewById(R.id.start2);
text2 = (TextView) findViewById(R.id.text2);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
connect();
}
});
start2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OkHttpClient client =new OkHttpClient.Builder()
.readTimeout(3, TimeUnit.SECONDS)
.build();
Request request =new Request.Builder()
.url("ws://echo.websocket.org")
.build();
WebSocket webSocket = client.newWebSocket(request, new WebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Response response) {
super.onOpen(webSocket, response);
}
@Override
public void onMessage(WebSocket webSocket, String text) {
super.onMessage(webSocket, text);
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
super.onMessage(webSocket, bytes);
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
super.onClosing(webSocket, code, reason);
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
super.onClosed(webSocket, code, reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
super.onFailure(webSocket, t, response);
}
});
}
});
}
/**
*WebSocket官网就提供了相应url可以测试
*/
private void connect() {
//建立连接
EchoWebSocketListener listener =new EchoWebSocketListener();
Request request =new Request.Builder()
.url("ws://echo.websocket.org")
.build();
OkHttpClient client =new OkHttpClient();
client.newWebSocket(request, listener);
client.dispatcher().executorService().shutdown();
}
/**
* 重写了WebSocketListener中的几个方法,这几个方法很好理解,是用来异步回调的,
* 这里简单说一下:onOpen当WebSocket和远程建立连接时回调;两个onMessage就是接收到消息时回调,
* 只是消息内容的类型不同;onClosing是当远程端暗示没有数据交互时回调(即此时准备关闭,但连接还没有关闭);
* onClosed就是当连接已经释放的时候被回调;onFailure当然是失败时被回调(包括连接失败,发送失败等)。
*
* send用来发送消息;close用来关闭连接
*/
private final class EchoWebSocketListenerextends WebSocketListener {
@Override
public void onOpen(WebSocket webSocket, Response response) {
webSocket.send("hello world");
webSocket.send("welcome");
webSocket.send(ByteString.decodeHex("adef"));
webSocket.close(1000, "再见");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
output("onMessage: " + text);
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
output("onMessage byteString: " + bytes);
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
webSocket.close(1000, null);
output("onClosing: " + code +"/" + reason);
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
output("onClosed: " + code +"/" + reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
output("onFailure: " + t.getMessage());
}
}
private void output(final String content) {
runOnUiThread(new Runnable() {
@Override
public void run() {
text.setText(text.getText().toString() +content +"\n");
}
});
}
}