Java: Multithreading & UDP Socket Programming
Posted
by Ravi
on Stack Overflow
See other posts from Stack Overflow
or by Ravi
Published on 2010-04-21T23:29:09Z
Indexed on
2010/04/21
23:33 UTC
Read the original article
Hit count: 210
I am new to multithreading & socket programming in Java. I would like to know what is the best way to implement 2 threads - one for receiving a socket and one for sending a socket. If what I am trying to do sounds absurd, pls let me know why! The code is largely inspired from Sun's tutorials online.I want to use Multicast sockets so that I can work with a multicast group.
class server extends Thread
{
static protected MulticastSocket socket = null;
protected BufferedReader in = null;
public InetAddress group;
private static class receive implements Runnable
{
public void run()
{
try
{
byte[] buf = new byte[256];
DatagramPacket pkt = new DatagramPacket(buf,buf.length);
socket.receive(pkt);
String received = new String(pkt.getData(),0,pkt.getLength());
System.out.println("From server@" + received);
Thread.sleep(1000);
}
catch (IOException e)
{ System.out.println("Error:"+e);
}
catch (InterruptedException e)
{ System.out.println("Error:"+e);
}
}
}
public server() throws IOException
{
super("server");
socket = new MulticastSocket(4446);
group = InetAddress.getByName("239.231.12.3");
socket.joinGroup(group);
}
public void run()
{
while(1>0)
{
try
{
byte[] buf = new byte[256];
DatagramPacket pkt = new DatagramPacket(buf,buf.length);
//String msg = reader.readLine();
String pid = ManagementFactory.getRuntimeMXBean().getName();
buf = pid.getBytes();
pkt = new DatagramPacket(buf,buf.length,group,4446);
socket.send(pkt);
Thread t = new Thread(new receive());
t.start();
while(t.isAlive())
{ t.join(1000);
}
sleep(1);
}
catch (IOException e)
{ System.out.println("Error:"+e);
}
catch (InterruptedException e)
{ System.out.println("Error:"+e);
}
}
//socket.close();
}
public static void main(String[] args) throws IOException
{
new server().start();
//System.out.println("Hello");
}
}
© Stack Overflow or respective owner