Java에서 멀티 스레드 프로그래밍 & 소켓 프로그래밍이 생소했습니다. 두 스레드를 구현하는 가장 좋은 방법은 무엇인지 알고 싶습니다. 하나는 소켓 수신 용이고 다른 하나는 소켓 전송 용입니다. 내가하려는 일이 터무니없는 소리로 들린다면, pls가 왜 그런지 알려주지! 이 코드는 주로 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
@Ravi, 서식을 수정했지만 클래스 이름을 편집해야합니다. 대문자로 시작해야합니다.수업 이름이 소문자로 시작하는 경우 코드를 읽는 것은 고통 스럽습니다. – Kiril
@Xepoch : 최종 목표는 분산 시스템에 특정 프로토콜을 구현하는 것입니다. @Lirik : 클래스 이름을 유감스럽게 생각합니다! 나는 그들을 지금 고쳤다. – Ravi