LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to broadcast with Java Socket (https://www.linuxquestions.org/questions/programming-9/how-to-broadcast-with-java-socket-689662/)

manolakis 12-10-2008 02:27 PM

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.

jay73 12-11-2008 01:00 PM

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

jlliagre 12-11-2008 04:11 PM

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).

arunmathew1984 12-14-2008 01:44 AM

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.