Вопрос

Here's my code for sending the string message in LAN on only one device or on one listening server and it is done by defining the IP of the server in client, both client and server programs are android app.But i want to broadcast the message so that all the listening server shall receive my message.

Here's my client code:

    public class MainActivity extends Activity {    
    private Socket socket;    
    private static final int SERVERPORT = 6000;
    private static final String SERVER_IP = "10.0.2.2";

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

        new Thread(new ClientThread()).start();
    }

    public void onClick(View view) {
        try {
            EditText et = (EditText) findViewById(R.id.EditText01);
            String str = et.getText().toString();
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),
                    true);
            out.println(str);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class ClientThread implements Runnable {

        @Override
        public void run() {

            try {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

                DatagramSocket = new Socket(serverAddr, SERVERPORT);

            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }    
        }    
    }}

Here is my server code:

    public class MainActivity extends Activity {    
    private DatagramSocket serverSocket;    
    Handler updateConversationHandler;    
    Thread serverThread = null;    
    private TextView text;    
    public static final int SERVERPORT = 6000;

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

        text = (TextView) findViewById(R.id.text2);

        updateConversationHandler = new Handler();

        this.serverThread = new Thread(new ServerThread());
        this.serverThread.start();    
    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class ServerThread implements Runnable {

        public void run() {
            Socket socket = null;
            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();
                }
            }
        }
    }

    class CommunicationThread implements Runnable {

        private Socket clientSocket;    
        private BufferedReader input;    
        public CommunicationThread(Socket clientSocket) {

            this.clientSocket = clientSocket;

            try {    
                this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));

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

        public void run() {    
            while (!Thread.currentThread().isInterrupted()) {

                try {    
                    String read = input.readLine();

                    updateConversationHandler.post(new updateUIThread(read));

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

    }

    class updateUIThread implements Runnable {
        private String msg;    
        public updateUIThread(String str) {
            this.msg = str;
        }

        @Override
        public void run() {
            text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
        }
    }}

What changing shall I made in client or server so that i can broadcast the string message in LAN and all the listening servers should receive,, Thanks in advance.Please kindly help.

Это было полезно?

Решение

Just try to get the broadcast address from network.this code may help you in order to extract the broadcast address.

 private InetAddress getBroadcastAddress() throws IOException {
DhcpInfo dhcp = mWifi.getDhcpInfo();
if (dhcp == null) {
  Log.d(TAG, "Could not get dhcp info");
  return null;
}

int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
  quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);}

Другие советы

You cannot use TCP for broadcasting messages. Try using UDP sockets via DatagramSocket

You would also need to set SO_BROADCAST option. By default, on most of the systems, broadcast is turned off. Please note that this socket option is a no-op for TCP since broadcast is not allowed for TCP (as Tishka noted).

http://www.beej.us/guide/bgnet/output/html/multipage/setsockoptman.html

you should use Network Service Discovery, the device broadcast the service (as server in your case) and also listen to the service at the same time:

https://developer.android.com/training/connect-devices-wirelessly/nsd.html

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top