- import java.net.*;
- import java.io.*;
- import java.awt.*;
- import java.awt.event.*;
- import java.util.*;
- import java.text.*;
- class Send implements Runnable
- {
- private DatagramSocket ds;
- private String text;
- Send(DatagramSocket ds,String text)
- {
- this.ds = ds;
- this.text = text;
- }
- public void run()
- {
- byte[] buf = text.getBytes();
- //封包
- try
- {
- DatagramPacket dp =
- new DatagramPacket(buf, buf.length,InetAddress.getByName("192.168.1.255"), 12005);
- ds.send(dp);
- }
- catch (Exception e)
- {
- throw new RuntimeException("接收端失败");
- }
- }
- }
- class Rece implements Runnable
- {
- private DatagramSocket ds;
- private TextArea ta;
- Rece(DatagramSocket ds,TextArea ta)
- {
- this.ds = ds;
- this.ta = ta;
- }
- public void run() {
- try {
- while (true)
- {
- byte[] buf = new byte[1024];
- DatagramPacket dp = new DatagramPacket(buf, buf.length);
- ds.receive(dp);//接收到数据就继续运行,没有就停在这了。
- String ip = dp.getAddress().getHostAddress();
- String data = new String(dp.getData(), 0, dp.getLength());
- System.out.println(ip + " : " + data);
- ta.append("("+ip+") "+Tools.getTime()+":\r\n"+data+"\r\n\r\n");
- }
- }catch (Exception e)
- {
- throw new RuntimeException("接收端失败");
- }
- }
- }
- class ChatDemo
- {
- private Frame f;
- private TextArea sendText,receText;
- private Button bt;
- ChatDemo()
- {
- init();
- }
- public void init()
- {
- f = new Frame("简易聊天");
- f.setBounds(300,240,430,500);
- f.setLayout(new FlowLayout()) ;
- receText = new TextArea(18,50); //接收文本域
- sendText = new TextArea(7,50); //输入文本域
- receText.setEditable(false); //禁止输入
- bt = new Button("发送");
- f.add(receText);
- f.add(sendText);
- f.add(bt);
- f.setVisible(true);
- event();
- }
- public void event()
- {
- //关闭窗口
- f.addWindowListener(new WindowAdapter()
- {
- public void windowClosing(WindowEvent e)
- {
- System.exit(0);
- }
- });
- //发送
- bt.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- try
- {
- if(!"".equals(sendText.getText()))
- {
- DatagramSocket sendSocket = new DatagramSocket();
- new Thread(new Send(sendSocket,sendText.getText())).start();
- sendText.setText(""); //发送完后,把输入文本域中的内容清空。
- }
- }
- catch (Exception ex)
- {
- throw new RuntimeException();
- }
- }
- });
- }
- public static void main(String[] args) throws Exception
- {
- ChatDemo cd = new ChatDemo();
- DatagramSocket receSocket = new DatagramSocket(12005);
- new Thread(new Rece(receSocket,cd.receText)).start();
- }
- }
- class Tools
- {
- //获取当前时间
- public static String getTime()
- {
- Date date =new Date();
- SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
- return sdf.format(date);
- }
- }
复制代码 请各位兄弟,看看我这代码写的有没有问题,如果能有两台机测试一下最好了。。。
|