溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Android設(shè)備之間通過Wifi通信的示例代碼

發(fā)布時(shí)間:2020-10-04 18:02:02 來源:腳本之家 閱讀:457 作者:sowhat4999 欄目:移動(dòng)開發(fā)

之前寫過PC與Android之間通過WIFI通信(通過Socket,可以在博客里面搜索),PC作為主機(jī),Android作為客戶機(jī),現(xiàn)在手頭有一臺(tái)儀器通過wifi傳輸數(shù)據(jù),如果儀器作為主機(jī)發(fā)射WIFI熱點(diǎn)信號(hào),Android需要連接到該熱點(diǎn)才能進(jìn)一步進(jìn)行通信,但是由于主機(jī)并沒有連接到網(wǎng)絡(luò),所以在該種情況下Android設(shè)備無法使用網(wǎng)絡(luò)實(shí)現(xiàn)相關(guān)的網(wǎng)絡(luò)服務(wù)(比如關(guān)鍵數(shù)據(jù)的上傳,網(wǎng)絡(luò)數(shù)據(jù)的獲取等等),所以儀器在開始設(shè)計(jì)的時(shí)候?qū)⑵渥鳛榭蛻舳?,Android設(shè)備作為主機(jī)(網(wǎng)上的相關(guān)資料大多是將Android設(shè)備作為客戶端),當(dāng)Android設(shè)備開啟熱點(diǎn)后,儀器會(huì)主動(dòng)嘗試連接固定的熱點(diǎn)信息,其中網(wǎng)絡(luò)SSID和密碼已經(jīng)寫死了,所以需要手機(jī)端手動(dòng)修改熱點(diǎn)名稱:

Android設(shè)備之間通過Wifi通信的示例代碼

Android設(shè)備之間通過Wifi通信的示例代碼

在開啟熱點(diǎn)之后,此時(shí)手機(jī)相當(dāng)于一個(gè)路由器,這個(gè)路由器的IP地址是固定的(本人測(cè)試過3臺(tái)Android設(shè)備,其默認(rèn)的路由器地址:192.168.43.1,iPhone的默認(rèn)路由器地址:172.20.10.1),這個(gè)Demo主要實(shí)現(xiàn)的目標(biāo)是Android設(shè)備客戶端發(fā)送信息,服務(wù)端接受到信息后再發(fā)送信息給客戶端。那么Android設(shè)備創(chuàng)建的SocketServer代碼如下:

只有一個(gè)按鈕,實(shí)現(xiàn)在線程中啟動(dòng)相對(duì)應(yīng)的服務(wù),所以在這里就不上圖了,直接放代碼:

package com.example.socketserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.koushikdutta.async.callback.CompletedCallback;
import com.koushikdutta.async.http.WebSocket;
import com.koushikdutta.async.http.WebSocket.StringCallback;
import com.koushikdutta.async.http.libcore.RequestHeaders;
import com.koushikdutta.async.http.server.AsyncHttpServer;
import com.koushikdutta.async.http.server.AsyncHttpServer.WebSocketRequestCallback;
import com.koushikdutta.async.http.server.AsyncHttpServerRequest;
import com.koushikdutta.async.http.server.AsyncHttpServerResponse;
import com.koushikdutta.async.http.server.HttpServerRequestCallback;
public class MainActivity extends Activity {
  private Button btnStart;
  private ServerSocket serverSocket;
  private BufferedReader in;
  private PrintWriter out;
  private Handler hander = new Handler(){

    @Override
    public void handleMessage(Message msg) {
      // TODO Auto-generated method stub
      super.handleMessage(msg);
      String s = (String)msg.obj;
      Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
    }
    
  };
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnStart = (Button)findViewById(R.id.button1);
    btnStart.setOnClickListener(new View.OnClickListener() {
      
      @Override
      public void onClick(View v) {
        // TODO Auto-generated method stub
        new ServerThread().start();//在新線程中啟動(dòng)SocketServer...
      }
    });    
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
      return true;
    }
    return super.onOptionsItemSelected(item);
  }
  @Override
  protected void onStop() {
    // TODO Auto-generated method stub
    super.onStop();
  }
  private class ServerThread extends Thread{

    @Override
    public void run() {
      // TODO Auto-generated method stub
      super.run();
      try {
//        serverSocket = new ServerSocket(50005);//默認(rèn)的路由器地址為Address: 192.168.43.1
        serverSocket = new ServerSocket(5000);
        while (true) {
          Socket clientSocket = serverSocket.accept();//阻塞等待處理...
           String remoteIP = clientSocket.getInetAddress().getHostAddress();
            int remotePort = clientSocket.getLocalPort();
            System.out.println("A client connected. IP:" + remoteIP+ ", Port: " + remotePort);  
          System.out.println("server: receiving.............");
          // 獲得 client 端的輸入輸出流,為進(jìn)行交互做準(zhǔn)備
          in = new BufferedReader(new InputStreamReader(
              clientSocket.getInputStream()));
          out = new PrintWriter(clientSocket.getOutputStream(), false);
          // 獲得 client 端發(fā)送的數(shù)據(jù)
          String tmp = in.readLine();
          // String content = new String(tmp.getBytes("utf-8"));
          System.out.println("Client message is: " + tmp);
          // 向 client 端發(fā)送響應(yīng)數(shù)據(jù)
          out.println("Your message has been received successfully!.");
          // 關(guān)閉各個(gè)流
          out.close();
          in.close();
           Message message = hander.obtainMessage();
           message.obj=tmp;
           hander.sendMessage(message);
           try {
            Thread.sleep(100);
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }      
    }    
  }
}

客戶端實(shí)現(xiàn)的代碼與網(wǎng)上相關(guān)的資料相差無幾,比較簡(jiǎn)單:

package com.example.serverclient;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
  private Button sendBtn,sendMessageBtn;
  private Socket socket;
  private PrintStream output;
  private BufferedInputStream bufferedInputStream;
  private ReadThread readThread;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sendBtn = (Button) findViewById(R.id.button1);
    sendMessageBtn = (Button) findViewById(R.id.button2);
    sendBtn.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        // TODO Auto-generated method stub
        new Thread(runnable).start();//開啟線程
      }
    });
    sendMessageBtn.setOnClickListener(new View.OnClickListener() {
      
      @Override
      public void onClick(View v) {
        // TODO Auto-generated method stub
         sendMessage("hello,i am from client message");
      }
    });
  }
  Runnable runnable = new Runnable() {
    
    @Override
    public void run() {
      // TODO Auto-generated method stub
      initClientSocket();
      readThread = new ReadThread();
      readThread.start();
    }
  };

  public void initClientSocket() {
    try {
      socket = new Socket("192.168.43.1", 5000);
      output = new PrintStream(socket.getOutputStream(), true, "gbk");

    } catch (UnknownHostException e) {
      // TODO Auto-generated catch block
      System.out.println("請(qǐng)檢查端口號(hào)是否為服務(wù)器IP");
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      System.out.println("服務(wù)器未開啟");
      e.printStackTrace();
    }
    output.println("this is the message from client");
  }
  public byte[] receiveData() {
    if (socket == null || socket.isClosed()) {
      try {
        socket = new Socket("192.168.43.1", 5000);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    byte[] data = null;
    if (socket.isConnected()) {
      try {
        bufferedInputStream = new BufferedInputStream(socket.getInputStream());
        data = new byte[bufferedInputStream.available()];
        bufferedInputStream.read(data);
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else {
      data = new byte[1];
    }
    return data;
  }
  private void sendMessage(String str) {
    output.println(str);
  }

  public void closeSocket() {
    try {
      output.close();
      socket.close();
    } catch (IOException e) {
      System.out.println("error"+e);
    }
  }
  private class ReadThread extends Thread{

    @Override
    public void run() {
      // TODO Auto-generated method stub
      super.run();
      while (true) {
        byte[] data = receiveData();
        if (data.length > 1) {
          System.out.println(new String(data));
        }
      }
    }
    
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
      return true;
    }
    return super.onOptionsItemSelected(item);
  }
}

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI