模拟QQ
import javax.swing.*;import java.awt.*;
import java.awt.event.*;
import *;
import *;
public class chat extends JFrame implements ActionListener
{
private JLabel label1,label2;
private JTextField textfield_ip;
private JTextArea textarea_receive,textarea_send;
private JButton button_send;
private JPanel panel1,panel2,panel3;
private DatagramPacket dpreceive;
private DatagramPacket dpsend;
private DatagramSocket ds;
private byte[] dbreceive;
private byte[] dbsend;
public chat()
{
this.panel1=new JPanel();
this.panel2=new JPanel();
this.panel3=new JPanel();
this.label1=new JLabel("请输入对方IP地址");
this.textfield_ip=new JTextField(20);
this.panel1.add(this.label1);
this.panel1.add(this.textfield_ip);
this.textarea_receive=new JTextArea(10,30);
this.textarea_send=new JTextArea(50,30);
this.panel2.add(this.textarea_receive);
this.panel2.add(this.textarea_send);
this.button_send=new JButton("发送");
this.button_send.addActionListener(this);
this.label2=new JLabel("");
this.panel3.add(this.button_send);
this.panel3.add(this.label2);
this.setSize(400,400);
this.setLayout(new BorderLayout());
this.add(panel1,BorderLayout.NORTH);
this.add(panel2,BorderLayout.CENTER);
this.add(panel3,BorderLayout.SOUTH);
this.setTitle("迷你QQ");
this.setForeground(Color.blue);
this.setLocation(300,300);
this.setDefaultCloseOperation(3);
this.setVisible(true);
try
{
this.ds=new DatagramSocket(2000);
this.dbreceive=new byte[100];
this.dpreceive=new DatagramPacket(this.dbreceive,dbreceive.length);
while(true)
{
for(int i=0;i<this.dbreceive.length;i++)
this.dbreceive[i]=0;
this.ds.receive(this.dpreceive);
String s=new String(this.dpreceive.getData()).trim();
this.textarea_receive.append("\n"+s);
}
}
catch(IOException e){System.out.println();}
}
public void actionPerformed(ActionEvent e)
{
String ip=this.textfield_ip.getText().trim();
String message=this.textarea_send.getText().trim();
if(ip.equals("")||message.equals(""))
{
this.label2.setText("IP为空或发送内容为空");
}
else
{
try
{
InetAddress ipdress=InetAddress.getByName(ip);
this.textarea_send.setText("");
this.textarea_receive.append("\n本人:"+message);
String messageto="["+InetAddress.getLocalHost()+"]"+message;
this.dbsend=messageto.getBytes();
this.dpsend=new DatagramPacket(this.dbsend,dbsend.length,ipdress,2000);
this.ds.send(this.dpsend);
}
catch(UnknownHostException uhe)
{
this.label2.setText("UnknownHostName");
}
catch(IOException ioe){}
}
}
public static void main(String []args)
{
new chat();
}
}