聊天程序

来源:互联网 发布:靳爱兵 程序员 编辑:程序博客网 时间:2024/04/28 04:14

通过网上搜索和自己的改动完成,通过UDP可以完成局域网内的聊天

import java.net.*;
import java.awt.*;
import java.awt.event.*;


import javax.swing.JFrame;


public class Receive extends JFrame {

TextField tfIP = new TextField(15);
TextArea lst = new TextArea();
Label lb = new Label("IP");
DatagramSocket ds;
TextField tfData = new TextField(20);
Button bt = new Button("send");
Button bt2 = new Button("Content can't for empty");
Dialog dlg = new Dialog(this, "消息提示", true);


public static void main(String args[]) {

new Receive();
}


public Receive() {
try {
ds = new DatagramSocket(8087);
} catch (Exception ex) {
ex.printStackTrace();
}


new Thread(new Runnable() {
public void run() {


byte buf[] = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
while (true) {
try {
ds.receive(dp);
lst.append("对方(来自" + dp.getAddress().getHostAddress()
+ ",接口:" + dp.getPort() + ") " + "当前时间:" + "\n"
+ new String(buf, 0, dp.getLength()) + "\n");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
init1();
}


public void init1() {
setSize(400, 400);
add(lst);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel();
p1.setLayout(new BorderLayout());
p2.setLayout(new BorderLayout());
p3.setLayout(new BorderLayout());
p1.add("West", lb);
p1.add("East", tfIP);
p2.add("West", bt);
p2.add("East", tfData);
p3.add("West", p1);
p3.add("East", p2);
add("South", p3);


dlg.setLayout(new FlowLayout());
dlg.add(bt2);
dlg.setBounds(0, 0, 200, 150);


setVisible(true);
setResizable(false);


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
//ds.close();
setVisible(false);
dispose();
System.exit(0);
}
});


bt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ex) {
byte[] buf;
buf = tfData.getText().getBytes();
if (buf.length != 0) {
try {
DatagramPacket dp = new DatagramPacket(buf, buf.length,
InetAddress.getByName(tfIP.getText()), 8088);
ds.send(dp);
tfData.setText("");
lst.append("我" + "\n" + new String(buf) + "\n");// new
// String(dp.getData());
} catch (Exception e) {
e.printStackTrace();
}
} else {
dlg.setModal(true);
dlg.setVisible(true);
}
}
});


bt2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dlg.dispose();

}
});


tfData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {


byte[] buf;
buf = e.getActionCommand().getBytes();
if (buf.length != 0) {
try {
DatagramPacket dp = new DatagramPacket(buf, buf.length,
InetAddress.getByName(tfIP.getText()), 8088);
ds.send(dp);
((TextField) e.getSource()).setText("");
lst.append("自己:" + "\n" + new String(buf) + "\n");// new
// String(dp.getData());
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
dlg.setModal(true);
dlg.setVisible(true);
}
}
});
}
}

0 0
原创粉丝点击