Android设备间通信(wifi连接)

基于TCP/IP协议实现:

1、首先在服务端新建ServerSocket类,指定端口号,利用其获取连接信息,得到Socket,之后的数据接收与发送,就可以通过这个Socket来进行实现。

server端主程序

package aw.com.wifi_connect_server;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
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.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {

    private TextView server_ip_port;
    private TextView client_ip_port;
    private TextView sendData;
    private String msg_send;
    private EditText message;
    private ServerSocket serverSocket = null;
    StringBuffer stringBuffer = new StringBuffer();
    private InputStream inputStream;
    private String IP=null;
    private int Port=0;
    private String clientIp;
    private int clientPort;
    private Socket socket = null;

    public Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            //super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    server_ip_port.setText(msg.obj.toString());
                    break;
                case 2:
                    message.setText(msg.obj.toString());
                    stringBuffer.setLength(0);
                    break;
                case 3:
                    client_ip_port.setText(msg.obj.toString());
                    break;
            }
        }
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        server_ip_port = (TextView) findViewById(R.id.server);
        client_ip_port = (TextView) findViewById(R.id.client);
        message = (EditText) findViewById(R.id.message_get);
        sendData = (EditText) findViewById(R.id.send_data);

        receiveData();
    }

    /*
    服务器端接收数据
    需要注意以下一点:
    服务器端应该是多线程的,因为一个服务器可能会有多个客户端连接在服务器上;
    */
    private void receiveData() {
        Thread thread = new Thread(){
            @Override
            public void run() {
                super.run();
                /*指明服务器端的端口号*/
                try {
                    serverSocket = new ServerSocket(8091);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (serverSocket!=null && !serverSocket.isClosed()){
                    Port = serverSocket.getLocalPort();
                }

                WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                int state = wifiManager.getWifiState();
                if (state == 3) {
                    WifiInfo info = wifiManager.getConnectionInfo();
                    IP = intIP2StringIP(info.getIpAddress());

                    Message message_1 = handler.obtainMessage();
                    message_1.what = 1;
                    message_1.obj = "IP:" + IP + " PORT: " + Port;
                    handler.sendMessage(message_1);


                    while (true) {
                        try {
                            if (serverSocket != null && !serverSocket.isClosed()) {
                                socket = serverSocket.accept();
                                clientIp = socket.getInetAddress().toString();
                                clientIp = clientIp.substring(1,clientIp.length());
                                clientPort = socket.getPort();
                                Message message_3 = handler.obtainMessage();
                                message_3.what = 3;
                                message_3.obj = "IP:" + clientIp + " PORT:" + clientPort;
                                handler.sendMessage(message_3);
                                inputStream = socket.getInputStream();
                                new ServerThread(socket, inputStream).start();

                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };
        thread.start();
    }

    private String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + ((ip >> 24) & 0xFF);
    }

    public void send(View view){
        msg_send = sendData.getText().toString();
        if (msg_send.isEmpty()){
            Toast.makeText(MainActivity.this, "Please input Sending data", Toast.LENGTH_SHORT).show();
        }
        msg_send = msg_send + "\0";
        Thread thread = new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    OutputStream outputStream = socket.getOutputStream();
                    outputStream.write(msg_send.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();
    }

    class ServerThread  extends Thread{
        private Socket socket;
        private InputStream   inputStream;
        private StringBuffer stringBuffer = MainActivity.this.stringBuffer;


        public ServerThread(Socket socket,InputStream inputStream){
            this.socket = socket;
            this.inputStream = inputStream;
        }

        @Override
        public void run() {
            int len;
            byte[] bytes = new byte[20];
            boolean isString = false;

            try {
                //在这里需要明白一下什么时候其会等于 -1,其在输入流关闭时才会等于 -1,
                //并不是数据读完了,再去读才会等于-1,数据读完了,最结果也就是读不到数据为0而已;
                while ((len = inputStream.read(bytes)) != -1) {
                    for(int i=0; i
server端页面
<?xml version="1.0" encoding="utf-8"?>

    
2、客户端,需知道服务器端的IP地址与端口号,然后才能依据server端的IP和端口号与server端建立连接,得到Socket,建立连接后,数据的接收与发送同样依赖于这一Socket。
client端主程序
package aw.com.wifi_connect_client;

import android.content.Context;
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.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class MainActivity extends AppCompatActivity {

    private EditText et_IP, et_data;
    private TextView local_ip_port;
    private String localIP;
    private int localPort;
    private OutputStream outputStream = null;
    private Socket socket = null;
    private String IP;
    private String data;
    private boolean socketStatus = false;
    private EditText message;
    private StringBuffer stringBuffer = new StringBuffer();
    private InputStream inputStream;

    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            //super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    local_ip_port.setText(msg.obj.toString());
                    break;
                case 2:
                    message.setText(msg.obj.toString());
                    stringBuffer.setLength(0);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et_IP = (EditText) findViewById(R.id.et_ip);
        et_data = (EditText) findViewById(R.id.et_data);
        local_ip_port = (TextView) findViewById(R.id.local_ip_port);
        message = (EditText) findViewById(R.id.message_get);


    }


    public void connect(View view) {
        IP = et_IP.getText().toString();
        if (IP.isEmpty()) {
            Toast.makeText(MainActivity.this, "Please input Server IP", Toast.LENGTH_SHORT).show();
        }
        Thread thread = new Thread() {

            @Override
            public void run() {
                super.run();

                WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                int state = wifiManager.getWifiState();

                if (!socketStatus && state == 3) {
                    try {
                        socket = new Socket(IP, 8091);
                        if (socket != null && !socket.isClosed()) {
                            localIP = socket.getLocalAddress().toString();
                            localIP = localIP.substring(1, localIP.length());
                            localPort = socket.getLocalPort();
                            Message message_1 = handler.obtainMessage();
                            message_1.what = 1;
                            message_1.obj = "IP:" + localIP + " PORT:" + localPort;
                            handler.sendMessage(message_1);
                            socketStatus = true;
                            outputStream = socket.getOutputStream();
                            receiveData();  //建立连接后,才可进行数据发送与数据接收
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        thread.start();
    }

    public void send(View view) {
        data = et_data.getText().toString();
        if (data.isEmpty()) {
            Toast.makeText(MainActivity.this, "Please input Sending Data", Toast.LENGTH_SHORT).show();
        }
        data = data + "\0";
        Thread thread = new Thread() {

            @Override
            public void run() {
                super.run();
                if (socketStatus) {
                    try {
                        outputStream.write(data.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        thread.start();
    }


    /**
     * 接收数据
     */
    private void receiveData() {
        Thread thread = new Thread() {
            @Override
            public void run() {
                super.run();

                try {
                    inputStream = socket.getInputStream();
                    new ServerThread(socket, inputStream).start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();
    }

    class ServerThread extends Thread{
        private Socket socket;
        private InputStream inputStream;
        private StringBuffer stringBuffer = MainActivity.this.stringBuffer;

        public ServerThread(Socket socket, InputStream inputStream) {
            this.socket = socket;
            this.inputStream = inputStream;
        }

        @Override
        public void run() {
            int len;
            byte[] bytes = new byte[20];
            boolean isString = false;

            try {
                //在这里需要明白一下什么时候其会等于 -1,其在输入流关闭时才会等于 -1,
                //并不是数据读完了,再去读才会等于-1,数据读完了,最结果也就是读不到数据为0而已;
                while ((len = inputStream.read(bytes)) != -1) {
                    for(int i=0; i
客户端页面
<?xml version="1.0" encoding="utf-8"?>

    

    
server端与client端页面效果
注意事项:
由于使用到了网络,故需要添加相应的权限,若缺少可能会出现如下错误
10-12 20:09:03.680 23977-24056/aw.com.wifi_connect_server W/System.err: java.net.SocketException: Permission denied
10-12 20:09:03.681 23977-24056/aw.com.wifi_connect_server W/System.err:     at java.net.ServerSocket.createImpl(ServerSocket.java:309)
10-12 20:09:03.681 23977-24056/aw.com.wifi_connect_server W/System.err:     at java.net.ServerSocket.getImpl(ServerSocket.java:258)
10-12 20:09:03.681 23977-24056/aw.com.wifi_connect_server W/System.err:     at java.net.ServerSocket.bind(ServerSocket.java:377)
10-12 20:09:03.681 23977-24056/aw.com.wifi_connect_server W/System.err:     at java.net.ServerSocket.<init>(ServerSocket.java:237)
10-12 20:09:03.681 23977-24056/aw.com.wifi_connect_server W/System.err:     at java.net.ServerSocket.<init>(ServerSocket.java:128)
10-12 20:09:03.681 23977-24056/aw.com.wifi_connect_server W/System.err:     at aw.com.wifi_connect_server.MainActivity$2.run(MainActivity.java:71)

在server与client的AndroidManifest.xml中添加相应权限
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />

没有更多推荐了,返回首页