1. 程式人生 > >websocket在android中的簡單使用

websocket在android中的簡單使用

如果你還對websocket不太瞭解,建議你先看一下我的這篇文章:

https://blog.csdn.net/Dongfnag_HU/article/details/84561758

好了,現在我們直接來看怎麼在android專案中使用websocket:

(這裡與我們通訊的伺服器是Echo WebSocket Server,詳情見其官網http:www.websocket.org/echo.html 

第一步:在你的module中新增相關的dependencies,如圖

 

第二步:在AndroidManifest.xml檔案中新增許可權

<uses-permission android:name="android.permission.INTERNET"/>

第三步:相關佈局檔案(一個開始的Button和顯示通訊資訊的TextView)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/activity_main"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.ssaurel.websocket.MainActivity">

<Button
 android:id="@+id/start"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:text="Start !"
 android:layout_marginTop="40dp"
 android:textSize="17sp"/>
 <TextView
 android:id="@+id/output"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@id/start"
 android:layout_centerHorizontal="true"
 android:textSize="16sp"
 android:layout_marginTop="30dp"/>
</RelativeLayout>

第四步:通訊

package com.ssaurel.websocket;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class MainActivity extends AppCompatActivity {
     private Button start;
     private TextView output;
     private OkHttpClient client;
     private final class EchoWebSocketListener extends WebSocketListener {
         private static final int NORMAL_CLOSURE_STATUS = 1000;
       
          @Override
         public void onOpen(WebSocket webSocket, Response response) {
             webSocket.send("Hello, it's SSaurel !");
             webSocket.send("What's up ?");
             webSocket.send(ByteString.decodeHex("deadbeef"));
             webSocket.close(NORMAL_CLOSURE_STATUS, "Goodbye !");
         }
         
          @Override
         public void onMessage(WebSocket webSocket, String text)
        {
             output("Receiving : " + text);
         }
         
        @Override
         public void onMessage(WebSocket webSocket, ByteString bytes) {
             output("Receiving bytes : " + bytes.hex());
         }

         @Override
         public void onClosing(WebSocket webSocket, int code,String reason) {
             webSocket.close(NORMAL_CLOSURE_STATUS, null);
             output("Closing : " + code + " / " + reason);
         }

         @Override
         public void onFailure(WebSocket webSocket, Throwable t,Response response) {
             output("Error : " + t.getMessage());
         }
     }

    @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     start = (Button) findViewById(R.id.start);
     output = (TextView) findViewById(R.id.output);
     client = new OkHttpClient();

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

 private void start() {
     Request request = new Request.Builder().url("ws://echo.websocket.org").build();
     EchoWebSocketListener listener = newEchoWebSocketListener();
     WebSocket ws = client.newWebSocket(request, listener);
     client.dispatcher().executorService().shutdown();
 }

 private void output(final String txt) {
     runOnUiThread(new Runnable() {
     @Override
     public void run() {
     output.setText(output.getText().toString() + "\n\n"+ txt);
     }
 });
 }
}

執行之後的結果大致是這樣的: