Android通过Socket实现局域网通信例子

最近工作上涉及比较多局域网连接和通信的业务需求,发现自己在这块一直是一个空缺,因此在网上找了一些资料,也在AS上试着验证,基本没有什么问题。

好了,不多说,直接上代码。

首先是Server端的代码实现:

1)MainActivity.java

package com.example.socketserver;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Handler;
import android.os.Message;

public class MainActivity extends AppCompatActivity {
    private TextView server_ip;
    private TextView server_textView;
    private EditText server_editText;
    private Button server_button;

    private SocketServer server;//启动服务端端口,服务端IP为手机IP
    private static final String TAG_LOG = "SocketServer_Actdebug";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        server_ip = (TextView)findViewById(R.id.server_ip);
        server_ip.setText("myip:"+getLocalIp());
        server_textView = (TextView)findViewById(R.id.server_textView);
        server_editText = (EditText) findViewById(R.id.server_editText);
        server_button = (Button) findViewById(R.id.server_button);

        server = new SocketServer(6666);
        server.beginListen();//socket服务端开始监听
        server_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                server.sendMessage(server_editText.getText().toString().trim());//socket发送数据
            }
        });

        SocketServer.ServerHandler = new Handler() {//socket收到消息线程
            @Override
            public void handleMessage(Message msg) {
                server_textView.setText(msg.obj.toString());
            }
        };
    }

    private String getLocalIp() {
        WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        if (0 == ipAddress) {
            return null;
        }
        return ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "."
                + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));

    }
}

2)SocketServer.java

package com.example.socketserver;

import android.os.Handler;
import android.os.Message;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
    private ServerSocket server;
    private Socket socket;
    private InputStream in;
    private String str = null;
    private boolean isClint = false;
    public static Handler ServerHandler;
    private static final String TAG_LOG = "SocketServer_debug";

    /**
     * @param port 端口号
     * @steps bind();绑定端口号
     * @effect 初始化服务端
     */
    public SocketServer(int port) {
        try {
            server = new ServerSocket(port);
            isClint = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @steps listen();
     * @effect socket监听数据
     */
    public void beginListen() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    socket = server.accept();//accept();接受请求
                    try {
                        in = socket.getInputStream();//得到输入流
                        while (!socket.isClosed()) {//实现数据循环接收
                            byte[] bt = new byte[50];
                            in.read(bt);
                            str = new String(bt, "UTF-8");//编码方式,解决收到数据乱码
                            if (str != null && str != "exit"){
                                returnMessage(str);
                            } else if (str == null || str == "exit") {
                                break;//跳出循环结束socket数据接收
                            }
                            System.out.println(str);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        socket.isClosed();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    socket.isClosed();
                }
            }
        }).start();
    }

    /**
     * @steps write();
     * @effect socket服务端发送信息
     */
    public void sendMessage(final String chat) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    PrintWriter out = new PrintWriter(socket.getOutputStream());
                    out.print(chat);
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * @steps read();
     * @effect socket服务端得到返回数据并发送到主界面
     */
    public void returnMessage(String chat) {
        Message msg = new Message();
        msg.obj = chat;
        ServerHandler.sendMessage(msg);
    }
}

接下来是Client端的代码实现:

1)MainActivity.java

package com.example.socketclient;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private TextView client_ip;
    private TextView client_textView;
    private EditText client_editText;
    private Button client_button;

    private SocketClient client;
    private static final String TAG_LOG = "SocketClient_Actdebug";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        client_ip = (TextView) findViewById(R.id.client_ip);
        client_ip.setText("ip:"+getLocalIp());
        client_textView = (TextView) findViewById(R.id.client_textView);
        client_editText = (EditText) findViewById(R.id.client_editText);
        client_button = (Button) findViewById(R.id.client_button);


        client = new SocketClient(this, "192.168.2.6", 6666);//服务端的IP地址和端口号
        client.openClientThread();//开启客户端接收消息线程

        client_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                client.sendMsg(client_editText.getText().toString().trim());//发送消息
            }
        });

        //接受消息
        SocketClient.ClientHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                client_textView.setText(msg.obj.toString());
                Log.d(TAG_LOG, msg.obj.toString());
            }
        };

    }

    private String getLocalIp() {
        WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        if (0 == ipAddress) {
            return null;
        }
        return ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "."
                + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));

    }
}package com.example.socketclient;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private TextView client_ip;
    private TextView client_textView;
    private EditText client_editText;
    private Button client_button;

    private SocketClient client;
    private static final String TAG_LOG = "SocketClient_Actdebug";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        client_ip = (TextView) findViewById(R.id.client_ip);
        client_ip.setText("ip:"+getLocalIp());
        client_textView = (TextView) findViewById(R.id.client_textView);
        client_editText = (EditText) findViewById(R.id.client_editText);
        client_button = (Button) findViewById(R.id.client_button);


        client = new SocketClient(this, "192.168.2.6", 6666);//服务端的IP地址和端口号
        client.openClientThread();//开启客户端接收消息线程

        client_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                client.sendMsg(client_editText.getText().toString().trim());//发送消息
            }
        });

        //接受消息
        SocketClient.ClientHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                client_textView.setText(msg.obj.toString());
                Log.d(TAG_LOG, msg.obj.toString());
            }
        };

    }

    private String getLocalIp() {
        WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        if (0 == ipAddress) {
            return null;
        }
        return ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "."
                + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));

    }
}

2)SocketClient.java

package com.example.socketclient;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;

public class SocketClient {
    private Socket clientSocket;
    private Context mContext;
    private String site;//端口
    private PrintWriter out;
    private InputStream mInputStream;
    private String getStr;
    private int port;//IP
    private boolean isClient = false;
    public static Handler ClientHandler;
    private static final String TAG_LOG = "SocketClient_debug";

    public SocketClient(Context context, String site, int port) {
        this.mContext = context;
        this.site = site;
        this.port = port;
    }

    //@effect 开启线程建立连接开启客户端
    public void openClientThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    clientSocket = new Socket(site, port);//connect()步骤
//                    client.setSoTimeout ( 5000 );//设置超时时间
//                    clientSocket = new Socket();
//                    SocketAddress socketAddress = new InetSocketAddress(site, port);
//                    clientSocket.connect(socketAddress, 3000);
                    if (clientSocket != null) {
                        isClient = true;
                        getOutString();
                        getInString();
                    } else {
                        isClient = false;
                        Toast.makeText(mContext, "网络连接失败 openClientThread", Toast.LENGTH_LONG).show();
                    }
                    Log.d(TAG_LOG, "site = " + site + " , port = " + port);
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                    Log.d(TAG_LOG, "UnknownHostException");
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.d(TAG_LOG, "IOException");
                }

            }
        }).start();
    }

    //得到输出字符串
    public void getOutString() {
        Log.d(TAG_LOG, "getOutString() invoked");
        try {
            out = new PrintWriter(clientSocket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
            Log.d(TAG_LOG, "getOutString() IOException");
        }
    }

    /**
     * @steps read();
     * @effect 得到输入字符串
     */
    public void getInString() {
        Log.d(TAG_LOG, "getInString() invoked");
        while (isClient) {
            try {
                mInputStream = clientSocket.getInputStream();
                byte[] bt = new byte[50];//得到的是16进制数,需要进行解析
                mInputStream.read(bt);
                getStr = new String(bt, "UTF-8");
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (getStr != null) {
                Message msg = new Message();
                msg.obj = getStr;
                ClientHandler.sendMessage(msg);
            }
        }
    }

    //@steps write();    @effect 发送消息
    public void sendMsg(final String str) {
        android.util.Log.d(TAG_LOG,"sendMsg str:"+str);
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (clientSocket != null) {
                    out.print(str);
                    out.flush();
                    Log.d(TAG_LOG, "client send message : " + str);
                } else {
                    isClient = false;
                }
            }
        }).start();
    }
}

最后是调试验证,分别拿两台Android系统手机连上同一个局域网,运行Server端的Demo看下对应的IP地址,然后将Client端的Demo上的ip改一下。最后分别在手机上运行即可。

其他注意:

1)布局和资源自行解决;

2)权限要注意,分别是网络权限和WLAN权限;

完整的工程代码可以到这里下载:

SocketDemo.rar-Java文档类资源-CSDN下载Android局域网连接通信Demo更多下载资源、学习资料请访问CSDN下载频道.https://download.csdn.net/download/lgglkk/41794776

你可能感兴趣的:(#,Application,android,java,socket)