Android connect to tethering socket

后端 未结 3 915
陌清茗
陌清茗 2020-12-15 03:42

I have 2 android devices, one acts as a server that is in tethering mode, and accepting connections to a port. The other device acts as a client that connects to the server

3条回答
  •  萌比男神i
    2020-12-15 04:18

    Server Side

    class ServerThread implements Runnable {
    
        public void run() {
            socket = new Socket();
    
            try {
                serverSocket = new ServerSocket(SERVERPORT);
            } catch (IOException e) {
                e.printStackTrace();
            }
            while (!Thread.currentThread().isInterrupted()) {
                try {
                        socket = serverSocket.accept();
    
                    CommunicationThread commThread = new CommunicationThread(socket);
                    new Thread(commThread).start();
    
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

    Client Side

    class ClientThread implements Runnable {
    
        @Override
        public void run() {
            try {
                socket = new Socket();
                InetSocketAddress socketAddress = new InetSocketAddress(SERVER_IP, SERVERPORT);
                socket.connect(socketAddress);
    
                CommunicationThread commThread = new CommunicationThread(socket);
                new Thread(commThread).start();
    
            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
    

提交回复
热议问题