¡Ø Multicast IP Address¸¦ ÀÌ¿ëÇÑ chatting
Multicast Ip address¸¦ ÀÌ¿äÇÑ Ã¤Æà ÇÁ·Î±×·¥ÀÔ´Ï´Ù.
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class Multicast implements Runnable, ActionListener {
private Frame f;
private TextField tf;
private TextArea ta;
private InetAddress group;
private MulticastSocket s;
public Multicast() {
f = new Frame("MulticatSocket Example");
tf = new TextField();
ta = new TextArea();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
try {
s.leaveGroup(group);
} catch(IOException ex) {
ex.printStackTrace();
}
System.exit(0);
}
});
tf.addActionListener(this);
f.add(ta);
f.add(tf,"South");
f.setSize(300,400);
f.setVisible(true);
try {
group = InetAddress.getByName("228.5.6.7");
s = new MulticastSocket(6789);
s.joinGroup(group);
}catch (Exception e){
e.printStackTrace();
}
}
public static void main(String args[]) {
Multicast cast = new Multicast();
Thread t = new Thread(cast);
t.start();
}
public void actionPerformed(ActionEvent e) {
String msg = tf.getText();
System.out.println("send data : "+msg);
DatagramPacket hi = new DatagramPacket(
msg.getBytes(), msg.getBytes().length,group, 6789
);
try {
s.send(hi);
}catch (IOException ex){
ex.printStackTrace();
}
tf.setText("");
}
public void run() {
try {
byte[] buf = new byte[1000];
while(true) {
DatagramPacket recv = new DatagramPacket(buf, buf.length);
System.out.println("listen..");
s.receive(recv);
String data = new String(recv.getData(),0,recv.getLength());
System.out.println("receive data : "+data);
InetAddress inet = recv.getAddress();
ta.append(inet.getHostAddress()+"] "+data+"\n");
}
}catch (Exception e){
e.printStackTrace();
}
}
}
¢º Multicast.java
2001.05.17 written by Jeon HongSeong
|