通过Android应用程序在LAN中广播消息

时间:2013-08-22 06:44:06

标签: android sockets udp client-server datagram

这是我在LAN中仅在一个设备或一个监听服务器上发送字符串消息的代码,它通过在客户端定义服务器的IP来完成,客户端和服务器程序都是android app.But我想要广播消息,以便所有侦听服务器都收到我的消息。

这是我的客户代码:

    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();
            }    
        }    
    }}

这是我的服务器代码:

    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");
        }
    }}

我应该在客户端或服务器上进行哪些更改,以便我可以在LAN中广播字符串消息,并且所有的侦听服务器都应该收到,请提前致谢。请帮助。

4 个答案:

答案 0 :(得分:0)

您无法使用TCP广播消息。尝试通过DatagramSocket

使用UDP套接字

答案 1 :(得分:0)

您还需要设置SO_BROADCAST选项。默认情况下,在大多数系统上,广播已关闭。请注意,这个套接字选项是TCP的无操作,因为TCP不允许广播(如Tishka所说)。

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

答案 2 :(得分:0)

只是尝试从网络获取广播地址。这段代码可以帮助您提取广播地址。

 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);}

答案 3 :(得分:0)

您应该使用网络服务发现,设备广播服务(在您的情况下作为服务器)并同时收听服务:

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