Android设备之间通过Wifi通信的示例代码

之前写过PC与Android之间通过WIFI通信(通过Socket,可以在博客里面搜索),PC作为主机,Android作为客户机,现在手头有一台仪器通过wifi传输数据,如果仪器作为主机发射WIFI热点信号,Android需要连接到该热点才能进一步进行通信,但是由于主机并没有连接到网络,所以在该种情况下Android设备无法使用网络实现相关的网络服务(比如关键数据的上传,网络数据的获取等等),所以仪器在开始设计的时候将其作为客户端,Android设备作为主机(网上的相关资料大多是将Android设备作为客户端),当Android设备开启热点后,仪器会主动尝试连接固定的热点信息,其中网络SSID和密码已经写死了,所以需要手机端手动修改热点名称:

成都创新互联公司专注于色尼企业网站建设,响应式网站设计,商城网站定制开发。色尼网站建设公司,为色尼等地区提供建站服务。全流程按需网站策划,专业设计,全程项目跟踪,成都创新互联公司专业和态度为您提供的服务

Android设备之间通过Wifi通信的示例代码

Android设备之间通过Wifi通信的示例代码

在开启热点之后,此时手机相当于一个路由器,这个路由器的IP地址是固定的(本人测试过3台Android设备,其默认的路由器地址:192.168.43.1,iPhone的默认路由器地址:172.20.10.1),这个Demo主要实现的目标是Android设备客户端发送信息,服务端接受到信息后再发送信息给客户端。那么Android设备创建的SocketServer代码如下:

只有一个按钮,实现在线程中启动相对应的服务,所以在这里就不上图了,直接放代码:

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();//在新线程中启动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);//默认的路由器地址为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 端的输入输出流,为进行交互做准备
          in = new BufferedReader(new InputStreamReader(
              clientSocket.getInputStream()));
          out = new PrintWriter(clientSocket.getOutputStream(), false);
          // 获得 client 端发送的数据
          String tmp = in.readLine();
          // String content = new String(tmp.getBytes("utf-8"));
          System.out.println("Client message is: " + tmp);
          // 向 client 端发送响应数据
          out.println("Your message has been received successfully!.");
          // 关闭各个流
          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();
      }      
    }    
  }
}

客户端实现的代码与网上相关的资料相差无几,比较简单:

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("请检查端口号是否为服务器IP");
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      System.out.println("服务器未开启");
      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);
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。


分享标题:Android设备之间通过Wifi通信的示例代码
文章转载:http://myzitong.com/article/gsjdec.html