How can I connect two Android device by socket without server

后端 未结 4 939
半阙折子戏
半阙折子戏 2021-02-08 12:14

I am trying to develop an android application that can exchange data on peer to peer connection with other devices without server. So please suggest how can I do this. Thank you

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-08 13:07

    This is a complete code for chat by SocketProgramming without server.

    In my Application, first you are a client and you search for a server. When you do not find any server, you become a server and wait for a client.

    public class MainActivity extends ActionBarActivity {
    
    private Handler handler = new Handler();
    private TextView text;
    private EditText input;
    private Button send;
    private Socket socket;
    private DataOutputStream outputStream;
    private BufferedReader inputStream;
    private String DeviceName = "Device";
    
    private boolean searchNetwork() {
        log("Connecting");
        String range = "192.168.56.";
        for (int i = 1; i <= 255; i++) {
            String ip = range + i;
            try {
                socket = new Socket();
                socket.connect(new InetSocketAddress(ip, 9000), 50);
                outputStream = new DataOutputStream(socket.getOutputStream());
                inputStream = new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));
                DeviceName += "1";
                Log.i("Server", DeviceName);
                log("Connected");
                return true;
            } catch (Exception e) {
            }
        }
        return false;
    
    }
    
    private void runNewChatServer() {
        ServerSocket serverSocket;
        try {
            serverSocket = new ServerSocket(9000);
            log("Waiting for client...");
            socket = serverSocket.accept();
            DeviceName += "2";
            log("a new client Connected");
        } catch (IOException e) {
        }
    
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (TextView) findViewById(R.id.text);
        input = (EditText) findViewById(R.id.input);
        send = (Button) findViewById(R.id.send);
        Thread thread = new Thread(new Runnable() {
    
            @Override
            public void run() {
                try {
                    if (!searchNetwork()) {
                        runNewChatServer();
    
                    }
    
                    outputStream = new DataOutputStream(
                            socket.getOutputStream());
                    inputStream = new BufferedReader(new InputStreamReader(
                            socket.getInputStream()));
                    while (true) {
    
                        String Message = inputStream.readLine();
                        if (Message != null) {
                            log(Message);
                        }
                    }
                } catch (IOException e) {
                    log("Error: IO Exception");
                    e.printStackTrace();
                }
            }
        });
        send.setOnClickListener(new OnClickListener() {
    
            @Override
            public void onClick(View arg0) {
                if (outputStream == null) {
                    return;
                }
                try {
                    String Message = input.getText().toString() + "\n";
                    outputStream.write(Message.getBytes());
                    log2(input.getText().toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                input.setText("");
            }
        });
        thread.start();
    
    }
    
    private void log(final String message) {
        handler.post(new Runnable() {
            String DeviceName2="";
            @Override
            public void run() {
                if (DeviceName.equals("Device1")) {
                    DeviceName2 = "Device2";
                }else if(DeviceName.equals("Device2")) {
                    DeviceName2 = "Device1";
                }else{
                    DeviceName2 = "UnknowDevice";
                }
    
                text.setText(text.getText() + "\n" + DeviceName2 + " :"
                        + message);
    
            }
        });
    }
    private void log2(final String message) {
        handler.post(new Runnable() {
    
            @Override
            public void run() {
    
    
                text.setText(text.getText() + "\n" + "you" + " :"
                        + message);
    
            }
        });
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            System.exit(0);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    }
    

提交回复
热议问题