网络知识 科技 Android实现WebSocke

Android实现WebSocke

WebSocket解决客户端发起多个http请求到服务器资源浏览器必需要通过长时间的轮询问题。socket

一种双向通讯协议,在创建链接后,WebSocket服务器和Browser/UA都能主动的向对方发送或接收数据,就像Socket同样,不一样的是WebSocket是一种创建在Web基础上的一种简单模拟Socket的协议;

下面是Android作为客户端连接webSocket服务器的实例介绍,如果你在阅读过程发现问题请告知我。

第一步:配置WebSocket

在app下build.gradle文件中配置WebSocket依赖项

…nndependencies {n …n implementation 'org.java-websocket:Java-WebSocket:1.5.2'n}n

提示:配置完成后刷新项目

第二步:添加网络权限

在AndroidManifest.xnl文件中添加网络权限

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

第三步:创建WebSocketClient(客户端)

新建一个类继承WebSocketClient类,实现WebSocketClient的四个抽象方法

npackage com.example.myapplication.tools;nnnimport org.java_websocket.client.WebSocketClient;nimport org.java_websocket.handshake.ServerHandshake;nnimport java.net.URI;nnpublic class MyWebSocket extends WebSocketClient {n public MyWebSocket(URI serverUri) {n super(serverUri);n }nn @Overriden public void onOpen(ServerHandshake handsHakedata) {n System.out.println("开始连接……."+handsHakedata);n }nn @Overriden public void onMessage(String message) {n System.out.println("开始通讯…….");n }nn @Overriden public void onClose(int code, String reason, boolean remote) {n System.out.println("断开连接…….");n }nn @Overriden public void onError(Exception ex) {n System.out.println("连接出错:"+ex);n }n}n

第四步: 创建连接连接

在MianActivity中实例化我们第三步新建的MyWebSocketClinet类;

nURI url = URI.create("ws://webSocket服务器地地址");nMyWebSocket myWebSocket = myWebSocket = new MyWebSocket(uri);nn//连接n try {n myWebSocket.connectBlocking();n System.out.println("连接状态:"+myWebSocket.isOpen();nn} catch (InterruptedException e) {n e.printStackTrace();n System.out.println("连接失败!"+e);n}nnn

第五步:发送消息

/先判断连接是否有效nif (+myWebSocket.isOpen()){ n myWebSocket.send("你好,我是新的myWebSocket客户端…");n}

测试

服务端:

Android实现WebSocke

webSocket服务端调试软件界面

Android客户端:

Android实现WebSocke

Android端界面效果

提示:

如果需要服务端软件和完整的源码工程请私信。

Android源码:

MyWebSocket.java

npackage com.example.myapplication.tools;nnimport org.java_websocket.client.WebSocketClient;nimport org.java_websocket.handshake.ServerHandshake;nnimport java.net.URI;nnpublic class MyWebSocket extends WebSocketClient {n public MyWebSocket(URI serverUri) {n super(serverUri);n }nn @Overriden public void onOpen(ServerHandshake handsHakedata) {n System.out.println("开始连接……."+handsHakedata);n }nn @Overriden public void onMessage(String message) {n System.out.println("开始通讯…….");n }nn @Overriden public void onClose(int code, String reason, boolean remote) {n System.out.println("断开连接…….");n }nn @Overriden public void onError(Exception ex) {n System.out.println("连接出错:"+ex);n }n}nnn

MainActivity.java

npackage com.example.myapplication;nnimport androidx.annotation.NonNull;nimport androidx.appcompat.app.AppCompatActivity;nnimport android.os.Bundle;nimport android.os.Handler;nimport android.os.Message;nimport android.util.Log;nimport android.view.Gravity;nimport android.view.View;nimport android.widget.Button;nimport android.widget.EditText;nimport android.widget.Toast;nnimport com.example.myapplication.tools.MyWebSocket;nnimport java.net.URI;nnpublic class MainActivity extends AppCompatActivity {n private Button btn_connect,btn_sendInfo; //连接和发送按钮n private EditText edit_address,edit_info; //地址和发送的内容输入框n private URI uri = null;n private String TAG = "info";n private Handler handler; //handler消息处理n private boolean connectState = false; //webSocket连接状态n private boolean sendState = false; //发送状态n private Toast toast;n private MyWebSocket myWebSocket; //我们继承WebSocketClient的MyWebSocket对象nn @Overriden protected void onCreate(Bundle savedInstanceState) {n super.onCreate(savedInstanceState);n setContentView(R.layout.activity_main);nn init();n btnClick();n handle();n }nnn //初始化界面和变量n private void init() {n btn_connect = findViewById(R.id.connect);n btn_sendInfo = findViewById(R.id.sendInfo);n edit_address = findViewById(R.id.address);n edit_info = findViewById(R.id.info);nn uri = URI.create("ws://192.168.2.159:8443/v1");n myWebSocket = new MyWebSocket(uri);n }nnn //按钮电机处理n private void btnClick() {n btn_connect.setOnClickListener(new View.OnClickListener() {n @Overriden public void onClick(View v) {n myWebSocket = new MyWebSocket(uri);nn //连接,因为网络操作开一个线程效果好一些n new Thread(new Runnable() {n @Overriden public void run() {n try {n myWebSocket.connectBlocking();n connectState = myWebSocket.isOpen();n Log.d(TAG, "连接状态: "+connectState);n Log.d(TAG, "ws地址: "+uri);n handler.sendEmptyMessage(1);nn } catch (InterruptedException e) {n e.printStackTrace();n }n }n }).start();n }n });nn n //发送n btn_sendInfo.setOnClickListener(new View.OnClickListener() {n @Overriden public void onClick(View v) {n String text = edit_info.getText().toString();n if (text.length()!=0){n if (connectState) {n sendState = sendMessage(text);n handler.sendEmptyMessage(2);n } else showToast("没有连接或连接无效!");n } else showToast("请先输入…");n }n });n }nnn private void handle() {n handler = new Handler(){n @Overriden public void handleMessage(@NonNull Message msg) {n super.handleMessage(msg);n switch (msg.what){n //处理连接n case 1:n if (connectState) showToast("连接成功!");n else showToast("连接失败,请重试!");n break;nn //处理发送n case 2:n if (sendState) showToast("发送成功");n else showToast("发送失败");n break;n }n }n };n }nn n //封装发送数据的函数n private boolean sendMessage(String text){n if (connectState){n myWebSocket.send(text);n return true;n }n return false;n }nnn //Toast提示函数n private void showToast(String text){n if (toast==null) toast = Toast.makeText(MainActivity.this,text,Toast.LENGTH_SHORT);n toast.setText(text);n toast.setGravity(Gravity.CENTER,0,0);n toast.show();n }nn}n

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>n<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"n xmlns:tools="http://schemas.android.com/tools"n android:layout_width="match_parent"n android:layout_height="match_parent"n android:orientation="vertical"n android:background="#E9EFE7"n android:padding="10dp"n tools:context=".MainActivity">nn <TextViewn android:layout_width="match_parent"n android:layout_height="wrap_content"n android:text="webSocket客户端通信测试"n android:gravity="center"n android:textColor="#000"n android:textSize="22sp"n android:layout_marginTop="100dp"n />n n <EditTextn android:id="@+id/address"n android:layout_width="match_parent"n android:layout_height="wrap_content"n android:hint="请输入服务器连接URL"n android:text="ws://127.0.0.1:8443/v1"n android:maxLines="1"n android:minLines="1"n android:inputType="textUri"n android:textColor="#000"n android:textSize="22sp"n android:layout_marginTop="100dp"n />nn <Buttonn android:id="@+id/connect"n android:layout_width="match_parent"n android:layout_height="wrap_content"n android:text="连 接"n android:gravity="center"n android:textColor="#FFFFFF"n android:textSize="22sp"n android:layout_margin="30dp"n />nn <LinearLayoutn android:layout_width="match_parent"n android:layout_height="wrap_content">nn <EditTextn android:id="@+id/info"n android:layout_width="0dp"n android:layout_weight="1"n android:layout_height="wrap_content"n android:hint="请输入发送内容"n android:text="hello"n android:textColor="#616161"/>n n <Buttonn android:id="@+id/sendInfo"n android:layout_width="wrap_content"n android:layout_height="wrap_content"n android:text="发送"n android:background="#00AA03"n android:gravity="center"n android:textColor="#FFFFFF"n />n </LinearLayout>nn</LinearLayout>

返回顶部