Site Search :
Standard Enterprise XML Methodology Pattern Setting Tunning Other
Article Contributors
GuestBook
Javapattern Maven
XSourceGen Dev
JetSpeed Test
JLook Image
jLook Family Site


Multicast IP address를 이용한 채팅
 
Multicast IP address를 이용한 채팅 ( 2003/02/28 ) 151
Written by specular - 전홍성
1 of 1
 

※ 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 
 
1
References
 
Copyright ⓒ 2003 www.javapattern.info & www.jlook.com, an jLOOK co.,LTD