How to broadcast with Java Socket
Hi there,
Does anybody know how can i broadcast a message with a Java Sockets implementation (tcp). Thank you. |
See the InetAddress API in the javadocs.
Basically, you would create a new Socket: Socket socket; OutputStream out; try{ InetAddress address = InetAddress.getByName("xxx.xxx.xxx.xxx") <--- IP address as String int port = xxxx; <--- client port socket = new Socket(address, port); out = socket.getOutputStream(); <---- obtain outputstream for writing to client(s) String msg = "..."; <--- message to client(s) byte [] output = msg.getBytes(); <---- convert msg to bytes; optionally specify a charset as an argument out.write(output); <--------- write output to client(s) out.flush(); <--- flush output so we are sure that it has been sent (failure to do so can cause client to hang) } catch (IOException iox){ }finally { try{ if (out != null) <-- first check whether we have an outputstream at all out.close(); <---- if so, close outputstream }catch (IOException iox){ } |
I'm afraid this sample code doesn't address the question.
Broadcasting can't be done with TCP Sockets which only support point to point (unicast) connected transmission. To broadcast, you need to use a UDP socket (DatagramSocket). You might also want to use multicasting (MulticastSocket). |
This looks like a homework question. Did you look up what you wanted on Google?
I did a simple search on your behalf, and came up with tons of good results: http://www.google.co.in/search?q=jav...ient=firefox-a Linux Archive |
All times are GMT -5. The time now is 03:36 PM. |