Anroid中两台手机连接同一wifi通过socket进行通信

Android设备连接局域网通过socket进行通信的原理是,一台设备作为服务端另外一台设备作为客户端开发。通过这种方法进行的通信做手机app的估计用得少,一般没人会连接局域网进行通信,但是在智能家居这一块估计用的会越来越多。今天就带来一个android通过socket进行通信的例子。

Android设备通过socket通信的简略图

一、Android局域网通信之服务端代码

<pre name="code" class="java">package com.example.androidsockettest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

	public static ServerSocket serverSocket = null;
	public static TextView mTextView, textView1;
    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();
				mTextView.append("client"+bundle.getString("msg")+"\n");
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mTextView = (TextView) findViewById(R.id.textsss);
		textView1 = (TextView) findViewById(R.id.textView1);
		IP = getlocalip();
		textView1.setText("IP addresss:"+IP);
		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("gbk"));
							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();
	}
	/**
	* 或取本机的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));  
	    } 
	
}

 二、 
Android局域网通信之客户端代码 

package com.example.client;

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;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
	Socket socket = null;
	String buffer = "";
	TextView txt1;
	Button send;
	EditText ed1;
	String geted1;
	public Handler myHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0x11) {
				Bundle bundle = msg.getData();
				txt1.append("server:"+bundle.getString("msg")+"\n");
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		txt1 = (TextView) findViewById(R.id.txt1);
		send = (Button) findViewById(R.id.send);
		ed1 = (EditText) findViewById(R.id.ed1);
		send.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				geted1 = ed1.getText().toString();
				txt1.append("client:"+geted1+"\n");
				//启动线程 向服务器发送和接收信息
				new MyThread(geted1).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.1.104", 30000), 1000); //端口号为30000
				//获取输入输出流
				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("gbk"));
				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();
			}
		}
	}

	

}


以上就是android局域网中利用socket通信的核心功能代码。

  • 12
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
要实现两台Android手机之间的WiFi热点通信,可以使用Android提供的Socket API和WifiManager API。 以下是基本步骤: 1. 创建WiFi热点 在一个手机上打开WiFi热点。您可以通过使用WifiManager类的setWifiApEnabled()方法来创建WiFi热点。例如: ``` WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiConfiguration wifiConfig = new WifiConfiguration(); wifiConfig.SSID = "MyWifiHotspot"; wifiConfig.preSharedKey = "password"; wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA); wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); Method setWifiApMethod = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class); setWifiApMethod.invoke(wifiManager, wifiConfig, true); ``` 2. 连接WiFi热点 在另一个手机连接WiFi热点。您可以使用WifiManager类的addNetwork()、enableNetwork()和reconnect()方法来连接WiFi热点。例如: ``` WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiConfiguration wifiConfig = new WifiConfiguration(); wifiConfig.SSID = "MyWifiHotspot"; wifiConfig.preSharedKey = "password"; wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA); wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); int networkId = wifiManager.addNetwork(wifiConfig); wifiManager.disconnect(); wifiManager.enableNetwork(networkId, true); wifiManager.reconnect(); ``` 3. 创建Socket连接 使用Socket API在手机之间创建Socket连接。在一个手机上作为服务器,另一个手机作为客户端。例如: 在服务器端: ``` ServerSocket serverSocket = new ServerSocket(8888); Socket socket = serverSocket.accept(); ``` 在客户端: ``` Socket socket = new Socket(serverIpAddress, 8888); ``` 4. 通过Socket传输数据 在Socket连接建立后,可以使用输入流和输出流来传输数据。在服务器端和客户端都需要使用输入流和输出流。例如: 在服务器端: ``` DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream()); dataOutputStream.writeUTF("Hello from server"); dataOutputStream.flush(); DataInputStream dataInputStream = new DataInputStream(socket.getInputStream()); String message = dataInputStream.readUTF(); ``` 在客户端: ``` DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream()); dataOutputStream.writeUTF("Hello from client"); dataOutputStream.flush(); DataInputStream dataInputStream = new DataInputStream(socket.getInputStream()); String message = dataInputStream.readUTF(); ``` 以上就是Android两台手机之间通过WiFi热点通信的基本步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值