import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
class Client implements WindowListener,ActionListener
{
Frame f;//定义窗口
Label lb1;//定义标签
Label lb2;
Label lb3;
Panel p1;//定义无边框
Panel p2;
Panel p3;
Button bt1;//定义按钮控件
TextField tf1;
TextArea ta;// 定义文本编辑区
TextField tf;// 定义文本编辑区
Button bt;
String hostname;//定义字符串 表示主机名称
String ip;
DatagramSocket receiveSocket, sendSocket;
DatagramPacket receivePacket ,sendPacket;
public static void main(String[] args)
{
Client client=new Client();
client.creatwindow();
client.start();
client.receiveMessage();
}
void creatwindow()
{
f=new Frame("Client Based on UDP Application");
p1=new Panel();
p2=new Panel();
p3=new Panel();
lb1=new Label("对话框");
lb2=new Label("发送消息");
lb3=new Label("服务器IP");
tf1=new TextField(30);
bt1=new Button("确定");
ta=new TextArea(10,55);
tf=new TextField(50);
bt=new Button("发送");
ta.setEditable(false);
p1.add(lb3);
p1.add(tf1);
p1.add(bt1);
p2.add(lb1);
p2.add(ta);
p3.add(lb2);
p3.add(tf);
p3.add(bt);
f.addWindowListener(this);
bt.addActionListener(this);
bt1.addActionListener(this);
f.add(p1,BorderLayout.NORTH);
f.add(p2,BorderLayout.CENTER);
f.add(p3,BorderLayout.SOUTH);
f.setSize(500,300);
f.setVisible(true);
f.setLocation(100,500);
}
public void windowClosing(WindowEvent e)
{
receiveSocket.close();
sendSocket.close();
System.exit(0);
}
public void windowClosed(WindowEvent e){}
public void windowOpened(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void start()
{
try
{
sendSocket=new DatagramSocket(5000);//客户机发送端口
}
catch(Exception e)
{
ta.append(e+"\n");
}
}
public void receiveMessage()//客户机发送消息
{
try
{
receiveSocket=new DatagramSocket(3000);//客户机接受端口
while(true)
{
byte[] buf=new byte[200];
receivePacket=new DatagramPacket(buf,buf.length);
receiveSocket.receive(receivePacket);
if(receivePacket.getLength()==0)
{
ta.append("空消息"+"\n");
continue;
}
ByteArrayInputStream bin=new ByteArrayInputStream(receivePacket.getData());
BufferedReader read=new BufferedReader(new InputStreamReader(bin));
ta.append("服务器:"+read.readLine());
ta.append("\n");
read.close();
bin.close();
}
}
catch(Exception e)
{
ta.append(e+"sendmessage error\n");
}
}
public void sendMessage()
{
try{
String s=tf.getText();
tf.setText("");
ta.append("客户机:"+s);
ta.append("\n");
ByteArrayOutputStream out=new ByteArrayOutputStream();
PrintStream pout=new PrintStream(out);
pout.print(s);
byte[] buf=out.toByteArray();
sendPacket=new DatagramPacket(buf,buf.length,InetAddress.getByName(ip),4000);
sendSocket.send(sendPacket);
buf=null;
}
catch(Exception e)
{
ta.append(e+"\n");
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==bt)
{
sendMessage();
}
else if(e.getSource()==bt1)
{
ip=tf1.getText();
tf1.setText("");
}
}
}