Android实现Socket通信

效果图

 

 用Idea创建一个java工程

import java.io.*;
import java.net.*;

public class Main {
    public static void main(String[] args) throws IOException {
        //1.创建一个服务器端Socket,即ServerSocket,指定绑定的端口,并监听此端口
        ServerSocket serverSocket = new ServerSocket(12345);
        InetAddress address = InetAddress.getLocalHost();
        String ip = address.getHostAddress();
        System.out.println("服务端ip地址: " + ip);
        while (true){
            Socket socket = serverSocket.accept();//it's a waiting task
            InputStream is = socket.getInputStream();     //获取输入流
            InputStreamReader isr = new InputStreamReader(is, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String info;
            while((info=br.readLine())!=null){//循环读取客户端的信息
                System.out.println(info);
                br = new BufferedReader(isr);
            }
            socket.shutdownInput();//关闭输入流
            socket.close();
        }

    }
}

Android的MainActivity

import android.os.Bundle;

import java.io.*;
import java.net.*;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new Thread() {
            @Override
            public void run() {
                try {
                    acceptServer();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();


    }
    private void acceptServer() throws IOException {
        //1.创建客户端Socket,指定服务器地址和端口
        Socket socket = new Socket("10.32.108.182", 12345);
        //2.获取输出流,向服务器端发送信息
        OutputStream os = socket.getOutputStream();//字节输出流
        PrintWriter pw = new PrintWriter(os);//将输出流包装为打印流
        pw.write("客户端:hello");
        pw.flush();
        socket.shutdownOutput();//关闭输出流
        socket.close();
    }
}

权限

 <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 

GitHub地址 下载前给star

这就是基本的原理,后面我打算做个聊天室

 

 

posted @ 2022-11-03 13:23  Z_Chan  阅读(468)  评论(0编辑  收藏  举报