简单界面:
思路:
1.先创建上图中的界面
2.添加相关的Event监听事件
3.使用多线程来设计发送端和接收端
4.在发送按钮里分别创建发送端和接收端的Thread启动线程。
5.最后在主程序分别传入发送和接收的DatagramSocket服务(保证唯一性)
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
class ChatDemo
{
public static void main(String[] args) throws SocketException,UnknownHostException
{
DatagramSocket send=new DatagramSocket();
DatagramSocket receive=new DatagramSocket(10001);
new FrameDemo(send,receive);
}
}
class FrameDemo
{
private Button clearBut;
private DatagramSocket send;
private DatagramSocket receive;
private Frame f;
private TextArea sendArea;
private TextArea receiveArea;
private Button but;
FrameDemo(DatagramSocket send,DatagramSocket receive)
{
this.send=send;
this.receive=receive;
init();
}
public void init()
{
f=new Frame("聊天面板");
f.setBounds(600,500,500,500);
f.setLayout(new FlowLayout());
sendArea=new TextArea();
receiveArea=new TextArea();
f.add(receiveArea);
f.add(sendArea);
clearBut=new Button("清屏");
but=new Button("发送");
f.add(clearBut);
f.add(but);
myEvent();
f.setVisible(true);
}
public void myEvent()
{
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
but.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
new Thread(new send(send,sendArea)).start();
new Thread(new receive(receive,receiveArea)).start();
}
});
clearBut.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
receiveArea.setText("");
}
});
}
}
//接收
class receive implements Runnable
{
private DatagramSocket ds;
private TextArea receiveArea;
receive(DatagramSocket ds,TextArea receiveArea)
{
this.ds=ds;
this.receiveArea=receiveArea;
}
public void run()
{
//创建数据包
byte[] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf,buf.length);
try
{
ds.receive(dp);
}
catch (IOException e)
{
throw new RuntimeException("接收端错误");
}
String ip=dp.getAddress().getHostAddress();
String data=new String(dp.getData(),0,dp.getLength());
receiveArea.append(ip+"\r\n"+data+"\r\n");
}
}
//发送端
class send implements Runnable
{
private TextArea sendArea;
private DatagramSocket ds;
send(DatagramSocket ds,TextArea sendArea)
{
this.ds=ds;
this.sendArea=sendArea;
}
public void run()
{
String sendData=sendArea.getText();
sendArea.setText("");
//创建数据包
byte[] buf=sendData.getBytes();
DatagramPacket dp=null;
try
{
dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),10001);
}
catch (UnknownHostException e)
{
throw new RuntimeException("发送端错误");
}
try
{
if(buf.length==0)
return;
ds.send(dp);
}
catch (IOException e)
{
throw new RuntimeException("发送端错误");
}
}
}