1. 程式人生 > 程式設計 >Android中socket通訊的簡單實現

Android中socket通訊的簡單實現

Android中socket通訊簡單實現,供大家參考,具體內容如下

socket通訊需要有一個伺服器和客戶端,可以把同一個APP作為伺服器跟客戶端,也可以分開成兩個APP。
先上個圖:

Android中socket通訊的簡單實現

這裡以一個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>

客戶端跟伺服器進行通訊之前記得先啟動伺服器,如果埠被佔用需要換個埠。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。