我是多線程新手& Java編程的套接字編程。我想知道什麼是實現2個線程的最佳方式 - 一個用於接收套接字,另一個用於發送套接字。如果我想要做的事聽起來很荒謬,請讓我知道爲什麼!代碼主要來自Sun的在線教程。我想使用多播套接字,以便我可以使用多播組。Java:多線程和UDP套接字編程
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 [email protected]" + 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");
}
}
你最終的目標是什麼? – Xailor 2010-04-21 23:48:43
@Ravi,我修正了你的格式,但你應該編輯類名......讓它們以大寫字母開頭。當你的班級名稱以小寫字母開頭時,閱讀你的代碼是很痛苦的。 – Kiril 2010-04-22 00:49:49
@Xepoch:我的最終目標是在分佈式系統中實現某些協議 @Lirik:對於類名稱感到抱歉!我現在修好了。 – Ravi 2010-04-22 12:44:22