- import java.awt.Button;
- import java.awt.FlowLayout;
- import java.awt.Frame;
- import java.awt.TextArea;
- import java.awt.event.MouseAdapter;
- import java.awt.event.MouseEvent;
- import java.awt.event.WindowAdapter;
- import java.awt.event.WindowEvent;
- import java.io.IOException;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- import java.net.SocketException;
- import java.net.UnknownHostException;
- public class TackTest {
- private Frame f;
- private Button b;
- private TextArea tf_1,tf_2;
- TackTest(){
- init();
- }
- public static void main(String[] args)throws Exception {
- new TackTest();
- }
- public void init(){
- f = new Frame("聊天窗口");
- f.setBounds(300, 200, 500, 400);
- f.setLayout(new FlowLayout());
- tf_1 = new TextArea(15,65);
- tf_2 = new TextArea(6,55);
- b = new Button("发送消息");
- f.add(tf_1);
- f.add(tf_2);
- f.add(b);
- tf_1.setEditable(false);
- rec();
- event();
- f.setVisible(true);
- }
- public void rec(){
- try {
- //建立UDP服务,监听端口。
- final DatagramSocket re = new DatagramSocket(10000);
- //建立一个线程,接收数据。
- new Thread(new Runnable() {
- @Override
- public void run() {
- while (true) {
- byte[] buf = new byte[1024];
- try {
- DatagramPacket dgp
- = new DatagramPacket(buf,buf.length);
- //接收数据包。
- re.receive(dgp);
- //拆包。
- String id = dgp.getAddress().getHostAddress();
- String data = new String(buf,0,dgp.getLength());
- //把数据写到接收消息窗口。
- tf_1.append(id + data + "\n");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }).start();
- } catch (SocketException e) {
- e.printStackTrace();
- }
- }
- private void event(){
- f.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e){
- System.exit(0);
- }
- });
- b.addMouseListener(new MouseAdapter() {
- public void mouseClicked(MouseEvent e){
- String str = tf_2.getText();
- try {
- //建立UDP服务。
- DatagramSocket dgs = new DatagramSocket();
- byte[] buf = str.getBytes();
- //把写的数据打。
- DatagramPacket dgp = new DatagramPacket(
- buf,
- buf.length,
- InetAddress.getByName("192.168.1.100"),
- 10000);
- //数据包发送。
- dgs.send(dgp);
- //清空发送窗口数据。
- tf_2.setText("");
- dgs.close();
- } catch (SocketException e1) {
- e1.printStackTrace();
- } catch (UnknownHostException e1) {
- e1.printStackTrace();
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- }
- });
- }
- }
复制代码 不晓得搞的这个代码可以不?哪里还要再优化下?
|