您好,登錄后才能下訂單哦!
Android中socket通信簡單實現,供大家參考,具體內容如下
socket通信需要有一個服務器和客戶端,可以把同一個APP作為服務器跟客戶端,也可以分開成兩個APP。
先上個圖:
這里以一個APP作為服務器跟客戶端為示例
1、添加網絡訪問權限
<uses-permission android:name="android.permission.INTERNET" />
2、寫服務器,在APP上啟動
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class Server { ServerSocket serverSocket = null; public final int port = 9998; private int i = 0; public Server(){ //輸出服務器的IP地址 try { InetAddress addr = InetAddress.getLocalHost(); System.out.println("local host:"+addr); serverSocket = new ServerSocket(port); System.out.println("0k"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void startService(){ try { Socket socket = null; System.out.println("waiting..."); //等待連接,每建立一個連接,就新建一個線程 while(true){ socket = serverSocket.accept();//等待一個客戶端的連接,在連接之前,此方法是阻塞的 System.out.println("connect to"+socket.getInetAddress()+":"+socket.getLocalPort()); new ConnectThread(socket).start(); } } catch (IOException e) { // TODO Auto-generated catch block System.out.println("IOException"); e.printStackTrace(); } } //向客戶端發送信息 class ConnectThread extends Thread{ Socket socket = null; public ConnectThread(Socket socket){ super(); this.socket = socket; } @Override public void run(){ try { DataInputStream dis = new DataInputStream(socket.getInputStream()); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); while(true){ i++; String msgRecv = dis.readUTF(); System.out.println("msg from client:"+msgRecv); dos.writeUTF(msgRecv + i); dos.flush(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
需要在線程中調用,調用方法:
new Thread(() -> new Server().startService()).start();
3、客戶端代碼
import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import androidx.appcompat.app.AppCompatActivity; /** * @author fenghaitao * @time 2020年4月2日14:34:33 * scoket客戶端連接測試 */ public class SocketActivity extends AppCompatActivity { //IP地址和端口號 public static String IP_ADDRESS = ""; public static int PORT = 9998; //三個控件 EditText et_message = null; //需要發送的內容 Button bt_getAdress = null; //獲取本機IP地址 Button bt_connect = null; //連接并發送 Button bt_startServer = null; //啟動服務端 TextView tv_adress = null; //ip地址 TextView tv_reply = null; //服務器回復的消息 //handler Handler handler = null; Socket soc = null; DataOutputStream dos = null; DataInputStream dis = null; String messageRecv = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_socket); et_message = findViewById(R.id.et_message); bt_getAdress = findViewById(R.id.bt_getAdress); bt_connect = findViewById(R.id.bt_connect); bt_startServer = findViewById(R.id.bt_startServer); tv_adress = findViewById(R.id.tv_adress); tv_reply = findViewById(R.id.tv_reply); bt_getAdress.setOnClickListener(v -> { new Thread(() -> { try { InetAddress addr = InetAddress.getLocalHost(); System.out.println("local host:"+addr); runOnUiThread(() -> tv_adress.setText(addr.toString().split("/")[1])); } catch (UnknownHostException e) { e.printStackTrace(); } }).start(); }); bt_startServer.setOnClickListener(v -> { new Thread(() -> new Server().startService()).start(); Toast.makeText(SocketActivity.this,"服務已啟動",Toast.LENGTH_SHORT).show(); }); bt_connect.setOnClickListener(v -> { IP_ADDRESS = tv_adress.getText().toString(); new ConnectionThread(et_message.getText().toString()).start(); }); handler = new Handler(msg -> { Bundle b = msg.getData(); //獲取消息中的Bundle對象 String str = b.getString("data"); //獲取鍵為data的字符串的值 tv_reply.append(str); return false; }); } //新建一個子線程,實現socket通信 class ConnectionThread extends Thread { String message = null; public ConnectionThread(String msg) { message = msg; } @Override public void run() { if (soc == null) { try { //Log.d("socket","new socket"); if ("".equals(IP_ADDRESS)) { return; } soc = new Socket(IP_ADDRESS, PORT); //獲取socket的輸入輸出流 dis = new DataInputStream(soc.getInputStream()); dos = new DataOutputStream(soc.getOutputStream()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { dos.writeUTF(message); dos.flush(); messageRecv = dis.readUTF();//如果沒有收到數據,會阻塞 Message msg = new Message(); Bundle b = new Bundle(); b.putString("data", messageRecv); msg.setData(b); handler.sendMessage(msg); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
下面是xml頁面代碼
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".SocketActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp"> <Button android:id="@+id/bt_getAdress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="獲取IP地址"/> <TextView android:id="@+id/tv_adress" android:layout_width="200dp" android:layout_height="match_parent" android:layout_marginLeft="15dp" android:textSize="20dp" android:gravity="center"/> </LinearLayout> <Button android:id="@+id/bt_startServer" android:text="啟動服務" android:layout_marginTop="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <EditText android:id="@+id/et_message" android:layout_marginTop="10dp" android:hint="請輸入發送信息" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <Button android:id="@+id/bt_connect" android:text="連接發送" android:layout_marginTop="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:id="@+id/tv_reply" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="服務端返回消息:" android:textSize="30sp"/> </LinearLayout> </LinearLayout>
客戶端跟服務器進行通信之前記得先啟動服務器,如果端口被占用需要換個端口。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。