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通信的核心功能代码。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐