前言:
此时看官们对“安卓 socket客户端”可能比较注意,我们都想要分析一些“安卓 socket客户端”的相关文章。那么小编在网摘上收集了一些对于“安卓 socket客户端””的相关内容,希望姐妹们能喜欢,兄弟们快快来学习一下吧!WebSocket解决客户端发起多个http请求到服务器资源浏览器必需要通过长时间的轮询问题。socket
一种双向通讯协议,在创建链接后,WebSocket服务器和Browser/UA都能主动的向对方发送或接收数据,就像Socket同样,不一样的是WebSocket是一种创建在Web基础上的一种简单模拟Socket的协议;
下面是Android作为客户端连接webSocket服务器的实例介绍,如果你在阅读过程发现问题请告知我。
第一步:配置WebSocket
在app下build.gradle文件中配置WebSocket依赖项
...dependencies { ... implementation 'org.java-websocket:Java-WebSocket:1.5.2'}
提示:配置完成后刷新项目
第二步:添加网络权限
在AndroidManifest.xnl文件中添加网络权限
...<uses-permission android:name="android.permission.INTERNET"/>...第三步:创建WebSocketClient(客户端)
新建一个类继承WebSocketClient类,实现WebSocketClient的四个抽象方法
package com.example.myapplication.tools;import org.java_websocket.client.WebSocketClient;import org.java_websocket.handshake.ServerHandshake;import java.net.URI;public class MyWebSocket extends WebSocketClient { public MyWebSocket(URI serverUri) { super(serverUri); } @Override public void onOpen(ServerHandshake handsHakedata) { System.out.println("开始连接......."+handsHakedata); } @Override public void onMessage(String message) { System.out.println("开始通讯......."); } @Override public void onClose(int code, String reason, boolean remote) { System.out.println("断开连接......."); } @Override public void onError(Exception ex) { System.out.println("连接出错:"+ex); }}第四步: 创建连接连接
在MianActivity中实例化我们第三步新建的MyWebSocketClinet类;
URI url = URI.create("ws://webSocket服务器地地址");MyWebSocket myWebSocket = myWebSocket = new MyWebSocket(uri);//连接 try { myWebSocket.connectBlocking(); System.out.println("连接状态:"+myWebSocket.isOpen();} catch (InterruptedException e) { e.printStackTrace(); System.out.println("连接失败!"+e);}第五步:发送消息
/先判断连接是否有效if (+myWebSocket.isOpen()){ myWebSocket.send("你好,我是新的myWebSocket客户端...");}测试
服务端:
Android客户端:
提示:
如果需要服务端软件和完整的源码工程请私信。Android源码:
MyWebSocket.java
package com.example.myapplication.tools;import org.java_websocket.client.WebSocketClient;import org.java_websocket.handshake.ServerHandshake;import java.net.URI;public class MyWebSocket extends WebSocketClient { public MyWebSocket(URI serverUri) { super(serverUri); } @Override public void onOpen(ServerHandshake handsHakedata) { System.out.println("开始连接......."+handsHakedata); } @Override public void onMessage(String message) { System.out.println("开始通讯......."); } @Override public void onClose(int code, String reason, boolean remote) { System.out.println("断开连接......."); } @Override public void onError(Exception ex) { System.out.println("连接出错:"+ex); }}
MainActivity.java
package com.example.myapplication;import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.util.Log;import android.view.Gravity;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;import com.example.myapplication.tools.MyWebSocket;import java.net.URI;public class MainActivity extends AppCompatActivity { private Button btn_connect,btn_sendInfo; //连接和发送按钮 private EditText edit_address,edit_info; //地址和发送的内容输入框 private URI uri = null; private String TAG = "info"; private Handler handler; //handler消息处理 private boolean connectState = false; //webSocket连接状态 private boolean sendState = false; //发送状态 private Toast toast; private MyWebSocket myWebSocket; //我们继承WebSocketClient的MyWebSocket对象 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); btnClick(); handle(); } //初始化界面和变量 private void init() { btn_connect = findViewById(R.id.connect); btn_sendInfo = findViewById(R.id.sendInfo); edit_address = findViewById(R.id.address); edit_info = findViewById(R.id.info); uri = URI.create("ws://192.168.2.159:8443/v1"); myWebSocket = new MyWebSocket(uri); } //按钮电机处理 private void btnClick() { btn_connect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { myWebSocket = new MyWebSocket(uri); //连接,因为网络操作开一个线程效果好一些 new Thread(new Runnable() { @Override public void run() { try { myWebSocket.connectBlocking(); connectState = myWebSocket.isOpen(); Log.d(TAG, "连接状态: "+connectState); Log.d(TAG, "ws地址: "+uri); handler.sendEmptyMessage(1); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } }); //发送 btn_sendInfo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String text = edit_info.getText().toString(); if (text.length()!=0){ if (connectState) { sendState = sendMessage(text); handler.sendEmptyMessage(2); } else showToast("没有连接或连接无效!"); } else showToast("请先输入..."); } }); } private void handle() { handler = new Handler(){ @Override public void handleMessage(@NonNull Message msg) { super.handleMessage(msg); switch (msg.what){ //处理连接 case 1: if (connectState) showToast("连接成功!"); else showToast("连接失败,请重试!"); break; //处理发送 case 2: if (sendState) showToast("发送成功"); else showToast("发送失败"); break; } } }; } //封装发送数据的函数 private boolean sendMessage(String text){ if (connectState){ myWebSocket.send(text); return true; } return false; } //Toast提示函数 private void showToast(String text){ if (toast==null) toast = Toast.makeText(MainActivity.this,text,Toast.LENGTH_SHORT); toast.setText(text); toast.setGravity(Gravity.CENTER,0,0); toast.show(); }}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="; xmlns:tools="; android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#E9EFE7" android:padding="10dp" tools:context=".MainActivity"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="webSocket客户端通信测试" android:gravity="center" android:textColor="#000" android:textSize="22sp" android:layout_marginTop="100dp" /> <EditText android:id="@+id/address" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入服务器连接URL" android:text="ws://127.0.0.1:8443/v1" android:maxLines="1" android:minLines="1" android:inputType="textUri" android:textColor="#000" android:textSize="22sp" android:layout_marginTop="100dp" /> <Button android:id="@+id/connect" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="连 接" android:gravity="center" android:textColor="#FFFFFF" android:textSize="22sp" android:layout_margin="30dp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/info" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:hint="请输入发送内容" android:text="hello" android:textColor="#616161"/> <Button android:id="@+id/sendInfo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="发送" android:background="#00AA03" android:gravity="center" android:textColor="#FFFFFF" /> </LinearLayout></LinearLayout>
标签: #安卓 socket客户端