簡單介面:
思路:
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("發送端錯誤"); } }}