package client;
import java.rmi.Naming;
import demo.inter;
import java.rmi.RemoteException;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class myclient extends JFrame implements ActionListener,Runnable{
JPanel ps,pn;
JTextArea text;
JLabel l,lname;
JButton b;
JTextField t;
static inter c;
byte buf[]=new byte[8192];
DatagramPacket pack;
static String name,serverip;
InetAddress net;
String local;
MulticastSocket ma=null;
InetAddress ress;
public myclient(){
super("client");
this.setSize(400,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try{
net=InetAddress.getLocalHost();
local=net.toString();
}catch(Exception ee){}
ps=new JPanel();
pn=new JPanel();
text=new JTextArea(20,40);
text.setEditable(false);
l=new JLabel(local+"客户机已经开启....");
lname=new JLabel(name);
b=new JButton("发送");
b.addActionListener(this);
t=new JTextField(16);
pn.add(l);
ps.add(lname);
ps.add(t);
ps.add(b);
this.getContentPane().add(pn,"North");
this.getContentPane().add(ps,"South");
this.getContentPane().add(new JScrollPane(text),"Center");
this.setVisible(true);
addWindowListener (new WindowAdapter() {
public void windowClosing (WindowEvent e){
try {
c = (inter)Naming.lookup( "rmi://"+serverip+":1099/Service");
c.talk(name+" : 已经退出聊天~~");
ma.leaveGroup(ress);
}catch (Exception ex) {
System.out.println("离开出错~~"+ex.toString());
}
setVisible(false);
System.exit(0);
}
});
Thread th=new Thread(this);
th.start();
}
public static void main(String[] args) {
JTextField message[]=new JTextField[4];
message[0]=new JTextField("请输入昵名:");
message[0].setEditable(false);
message[1]=new JTextField();
message[2]=new JTextField("请输入服务器IP:");
message[2].setEditable(false);
message[3]=new JTextField();
String str[]={"确认","取消"};
int go=JOptionPane.showOptionDialog(null, message, "用户登陆",JOptionPane.YES_OPTION, JOptionPane.INFORMATION_MESSAGE, null, str, str[0]);
if(go==0){
name=message[1].getText();
serverip=message[3].getText();
try{
c = (inter)Naming.lookup( "rmi://"+serverip+":1099/Service");
c.talk("欢迎"+name+"来到聊天室!");
}catch(Exception er){}
new myclient();
}
}
public void actionPerformed(ActionEvent e){
try {
c = (inter)Naming.lookup( "rmi://"+serverip+":1099/Service");
c.talk(name+" : "+t.getText()+"");
t.setText("");
}catch (Exception ex) {}
}
public void run(){
pack=new DatagramPacket(buf,buf.length);
try {
ma=new MulticastSocket(666);
ress=InetAddress.getByName("192.168.76.212");
ma.joinGroup(ress);
} catch (Exception ex) {}
while (true) {
if (ma==null) {
break;
} else {
try {
ma.receive(pack);
} catch (Exception ex1) {}
String s=new String(pack.getData(),0,pack.getLength());
text.setText(text.getText()+s+"\n");
}
}
}
}