以前学习过java,但是一直没接触到网络编程这一块,现在要把这一个知识盲点扫除掉
import java.awt.*;
import java.net.*;
import java.awt.event.*;
public class Chat extends Frame {
List lst = new List(6);
TextField tfIP = new TextField(15);
TextField tfData = new TextField(20);
//发送端
DatagramSocket ds = null;
public Chat(){
try {
ds = new DatagramSocket(3000);
}catch (Exception e) {
e.printStackTrace();
}
this.add(lst,"Center");
Panel p = new Panel();
this.add(p,"South");
p.setLayout(new BorderLayout());
p.add(tfIP,"West");
p.add(tfData,"East");
//接收线程
new Thread(new Runnable(){
public void run(){
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
while(true){
try{
ds.receive(dp);
//最新消息放首行
lst.add(new String(buf,0,dp.getLength())
+" "+dp.getAddress().getHostAddress()+":"+dp.getPort()
,0);
}catch(Exception e){
//当Socket结束了,接收方法会出现异常
if(!ds.isClosed()){
System.out.print("接收端");
e.printStackTrace();
}
}
}
}
}).start();
tfData.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//获取消息和IP
byte[] buf = tfData.getText().getBytes();
try{
DatagramPacket dp = new DatagramPacket(
buf,buf.length,
InetAddress.getByName(tfIP.getText()),
3000);
ds.send(dp);
}catch(Exception e1){
e1.printStackTrace();
}
tfData.setText("");
}
});
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
ds.close();//关闭Socket
dispose();
System.exit(0);
}
});
}
public static void main(String[] args) {
Chat chat = new Chat();
chat.setTitle("聊天窗口");
chat.setBounds(300,200,300,400);
chat.setVisible(true);
chat.setResizable(false);
}
}
|
|