欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android使用Socket连接同一WiFi进行通信的实际操作讲解

程序员文章站 2022-05-01 17:46:00
在同一局域网的情况下,两台设备想要进行通信,就需要用到socket,原理就是一台设备作为服务端(主要为serversocket类),另一台作为客户端(socket)。 这次目的是一台手机作为客户端,...

在同一局域网的情况下,两台设备想要进行通信,就需要用到socket,原理就是一台设备作为服务端(主要为serversocket类),另一台作为客户端(socket)。

这次目的是一台手机作为客户端,具有自动扫描二维码请将扫描结果传递给服务器,另一台手机作为服务器,接收数据经进行解析的功能。

一、服务器端代码

package comvoice.example.zhangbin.flysocketservice;

import android.content.context;
import android.net.wifi.wifiinfo;
import android.net.wifi.wifimanager;
import android.os.handler;
import android.os.message;
import android.support.v7.app.appcompatactivity;
import android.os.bundle;
import android.widget.textview;

import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstreamreader;
import java.io.outputstream;
import java.net.serversocket;
import java.net.socket;

public class mainactivity extends appcompatactivity {

 public static serversocket serversocket = null;
 public static textview tv_ip, tv_show;
 private string ip = "";
 string buffer = "";
 public static handler mhandler = new handler() {
  @override
  public void handlemessage(android.os.message msg) {
if (msg.what==0x11) {
 bundle bundle = msg.getdata();
// tv_show.settext("client:  "+bundle.getstring("msg")+"\n");
 initjx(bundle.getstring("msg"));
}
  };
 };

 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_main);
  initview();
  receive();

 }

 private void initview() {
  tv_show = (textview) findviewbyid(r.id.tv_show);
  tv_ip = (textview) findviewbyid(r.id.tv_ip);
  ip = getlocalip();
  tv_ip.settext("ip addresss:"+ip);
 }
 private void receive(){
  new thread() {
public void run() {
 bundle bundle = new bundle();
 bundle.clear();
 outputstream output;
 string str = "hello hehe";
 try {
  serversocket = new serversocket(30000);
  while (true) {
message msg = new message();
msg.what = 0x11;
try {
 socket socket = serversocket.accept();
 output = socket.getoutputstream();
 output.write(str.getbytes("utf-8"));
 output.flush();
 socket.shutdownoutput();
 bufferedreader bff = new bufferedreader(new inputstreamreader(socket.getinputstream()));
 string line = null;
 buffer = "";
 while ((line = bff.readline())!=null) {
  buffer = line + buffer;
 }
 bundle.putstring("msg", buffer.tostring());
 msg.setdata(bundle);
 mhandler.sendmessage(msg);
 bff.close();
 output.close();
 socket.close();
} catch (ioexception e) {
 e.printstacktrace();
}
  }
 } catch (ioexception e1) {
  // todo auto-generated catch block
  e1.printstacktrace();
 }
};
  }.start();
 }

 //解析二维码信息
 private static void initjx(string data){
  string []an=data.split("\\+");
  tv_show.settext(an[0]+"::"+an[1]+"::"+an[2]+"::"+an[3]);
 }

 /**
  * 或取本机的ip地址
  */
 private string getlocalip(){
  wifimanager wifimanager = (wifimanager)getsystemservice(context.wifi_service);
  wifiinfo wifiinfo = wifimanager.getconnectioninfo();
  int ipaddress = wifiinfo.getipaddress();
  //  log.d(tag, "int ip "+ipaddress);
  if(ipaddress==0)return null;
  return ((ipaddress & 0xff)+"."+(ipaddress>>8 & 0xff)+"."
 +(ipaddress>>16 & 0xff)+"."+(ipaddress>>24 & 0xff));
 }

}

二、客户端代码

package comvoice.example.zhangbin.flysocketclient;

import android.content.intent;
import android.os.handler;
import android.os.message;
import android.support.v7.app.appcompatactivity;
import android.os.bundle;
import android.view.view;
import android.widget.button;
import android.widget.edittext;
import android.widget.textview;

import com.tbruyelle.rxpermissions.rxpermissions;

import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstreamreader;
import java.io.outputstream;
import java.net.inetsocketaddress;
import java.net.socket;
import java.net.sockettimeoutexception;

public class mainactivity extends appcompatactivity implements view.onclicklistener{

 socket socket = null;
 string buffer = "";
 textview tv_show;
 button bt_send,bt_scan;
 edittext et_input;
 string geted1;
 rxpermissions rxpermissions;
 public handler myhandler = new handler() {
  @override
  public void handlemessage(message msg) {
if (msg.what == 0x11) {
 bundle bundle = msg.getdata();
 tv_show.append("server:"+bundle.getstring("msg")+"\n");
//每次客户端传输完数据后,再次调用扫描功能,实现连续扫描的功能(应该有更好的方法,暂时不知道)
 startactivityforresult(new intent(mainactivity.this, scanningactivity.class), 1);
}
  }
 };

 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_main);
  initview();
  initclick();
 }

 private void initclick() {
  bt_scan.setonclicklistener(this);
  bt_send.setonclicklistener(this);
 }

 @override
 public void onclick(view view) {
  switch (view.getid()){
case r.id.bt_scan:
 startactivityforresult(new intent(mainactivity.this, scanningactivity.class), 1);
 break;
case r.id.bt_send:
 geted1 = et_input.gettext().tostring();
 tv_show.append("client:"+geted1+"\n");
 //启动线程 向服务器发送和接收信息
 new mythread(geted1).start();
 break;
 default:
  break;
  }
 }
 private void initview() {
  tv_show = (textview) findviewbyid(r.id.tv_show);
  bt_send = (button) findviewbyid(r.id.bt_send);
  et_input = (edittext) findviewbyid(r.id.et_input);
  bt_scan=findviewbyid(r.id.bt_scan);
 }

 @override
 public void onactivityresult(int requestcode, int resultcode, intent data) {
  super.onactivityresult(requestcode, resultcode, data);
  if(resultcode==result_ok){
  if(requestcode==1){
 new mythread(data.getstringextra("text")).start();
}
  }
 }
 class mythread extends thread {

  public string txt1;

  public mythread(string str) {
txt1 = str;
  }

  @override
  public void run() {
//定义消息
message msg = new message();
msg.what = 0x11;
bundle bundle = new bundle();
bundle.clear();
try {
 //连接服务器 并设置连接超时为1秒
 socket = new socket();
 socket.connect(new inetsocketaddress("192.168.0.130", 30000), 1000); //端口号和ip更换为自己的,也可以手动输入
 //获取输入输出流
 outputstream ou = socket.getoutputstream();
 bufferedreader bff = new bufferedreader(new inputstreamreader(
socket.getinputstream()));
 //读取发来服务器信息
 string line = null;
 buffer="";
 while ((line = bff.readline()) != null) {
  buffer = line + buffer;
 }

 //向服务器发送信息
 ou.write(txt1.getbytes("utf-8"));
 ou.flush();
 bundle.putstring("msg", buffer.tostring());
 msg.setdata(bundle);
 //发送消息 修改ui线程中的组件
 myhandler.sendmessage(msg);
 //关闭各种输入输出流
 bff.close();
 ou.close();
 socket.close();

} catch (sockettimeoutexception aa) {
 //连接超时 在ui界面显示消息
 bundle.putstring("msg", "服务器连接失败!请检查网络是否打开");
 msg.setdata(bundle);
 //发送消息 修改ui线程中的组件
 myhandler.sendmessage(msg);
} catch (ioexception e) {
 e.printstacktrace();
}
  }
 }

}
package comvoice.example.zhangbin.flysocketclient;

import android.content.intent;
import android.os.bundle;
import android.support.v7.app.appcompatactivity;

import com.google.zxing.result;

import me.dm7.barcodescanner.zxing.zxingscannerview;

public class scanningactivity extends appcompatactivity implements zxingscannerview.resulthandler{
 private zxingscannerview mzxingscannerview;

 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_scanning);
  mzxingscannerview = new zxingscannerview(this); // 将zxingscannerview作为布局
  setcontentview(mzxingscannerview);
 }
 @override
 protected void onresume() {
  super.onresume();
  mzxingscannerview.setresulthandler(this); // 设置处理结果回调

  mzxingscannerview.startcamera(); // 打开摄像头

 }

 @override
 protected void onpause() {
  super.onpause();
  mzxingscannerview.stopcamera(); // 活动失去焦点的时候关闭摄像头
 }

 @override
 public void handleresult(result result) { // 实现回调接口,将数据回传并结束活动
  intent data = new intent();
  data.putextra("text", result.gettext());
  setresult(result_ok, data);
  finish();
 }
}