- //package MyQQ;
- import java.io.*;
- import java.net.*;
- import java.awt.*;
- import java.awt.event.*;
- class MyQQ
- {
- public static void main(String[] args)throws Exception
- {
- new MyWindow();
- new Send(new DatagramSocket());
- Thread t = new Thread(new Rece(new DatagramSocket(10000)));
- t.start();
- //Thread t1 = new Thread(new Send(new DatagramSocket()));
- //Thread t2 = new Thread(new Rece(new DatagramSocket(10000)));
- //t1.start();
- //t2.start();
-
- //System.out.println("Hello World!");
- }
- }
- class MyWindow
- {
- private Frame f;
- public static TextArea ta;
- public static TextField tf;
- private Button but;
- public static String str;
- public MyWindow()
- {
- init();
- }
- public void init()
- {
- f = new Frame("MyQQ");
- f.setBounds(300,100,500,650);
- f.setLayout(new FlowLayout());
-
- ta = new TextArea(35,60);
- tf = new TextField(50);
- but = new Button("发送");
-
- f.add(ta);
- f.add(tf);
- f.add(but);
- myEvent();
- f.setVisible(true);
- }
- private void myEvent()
- {
- f.addWindowListener(new WindowAdapter()
- {
- public void windowClosing(WindowEvent e)
- {
- System.exit(0);
- }
- });
- but.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- Send.send();
- }
- });
- tf.addKeyListener(new KeyAdapter()
- {
- public void keyPressed(KeyEvent e)
- {
- if (e.getKeyCode()==KeyEvent.VK_ENTER)
- Send.send();
- }
- });
- }
- }
- class Send implements Runnable
- {
- private static DatagramSocket ds;
- private static String line;
- public Send(DatagramSocket ds)
- {
- this.ds = ds;
- }
- public void run()
- {
- send();
- }
- public static void send()
- {
- try
- {
- line =MyWindow.tf.getText();
- //while (!(line=="over"))
- //{
- //MyWindow.ta.append(line+"\r\n");
- byte[] buf = line.getBytes();
- DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.0.255"),10000);
- ds.send(dp);
- MyWindow.tf.setText(null);
-
- //}
- //System.exit(0);
- }
- catch (Exception e)
- {
- throw new RuntimeException("发送异常");
- }
- }
- }
- class Rece implements Runnable
- {
- private DatagramSocket ds;
- public Rece(DatagramSocket ds)
- {
- this.ds = ds;
- }
- public void run()
- {
- try
- {
- while (true)
- {
- byte[] buf = new byte[1024];
- DatagramPacket dp = new DatagramPacket(buf,buf.length);
- ds.receive(dp);
- String s = new String(dp.getData(),0,dp.getLength());
- MyWindow.ta.append(s+"\r\n");
- System.out.println(s);
- }
-
- }
- catch (Exception e)
- {
- throw new RuntimeException("接收异常");
- }
- }
- }
复制代码 |