基于UDP协议的Java聊天小程序!

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
import java.text.*;
public class Test extends JFrame{
 JPanel p1=new JPanel();
 JPanel p2=new JPanel();
 JLabel lb1=new JLabel();
 JLabel lb2=new JLabel("for ligson");
 JLabel lb3=new JLabel("IPAddress:");
 JLabel lb4=new JLabel("ChatInfo:");
 java.awt.List lst=new java.awt.List(10);
 JTextField tfIP=new JTextField(15);
 JTextField tfInfo=new JTextField(6);
 DatagramSocket ds;
 Test(){
  try{
   ds=new DatagramSocket(9999);
  }catch(IOException e){
   e.printStackTrace();
  }
  this.setVisible(true);
  this.setBounds(200,200,300,400);
  //this.setBackground(Color.GREEN);
  this.add(p1,"North");
  this.add(p2,"South");
  this.add(lst,"Center");
  this.setTitle("MyChat");
  p1.setLayout(new GridLayout(1,2));
  p2.setLayout(new GridLayout(2,2));
  p1.add(lb1);
  p1.add(lb2);
  p2.add(lb3);
  p2.add(lb4);
  p2.add(tfIP);
  p2.add(tfInfo);
  /*lst.setBackground(Color.BLACK);
  lst.setForeground(Color.GREEN);
  tfIP.setBackground(Color.BLACK);
  tfIP.setForeground(Color.GREEN);
  tfInfo.setBackground(Color.BLACK);
  tfInfo.setForeground(Color.GREEN);*/
  this.pack();
  this.addWindowListener(new WindowAdapter(){
   public void windowClosing(WindowEvent e){
    System.exit(0);
   }
  });
  tfInfo.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent e){
    try{
     String ssInfo=tfInfo.getText();
     byte[] buf=ssInfo.getBytes();
     String sip=tfIP.getText().trim();
     String name=InetAddress.getLocalHost().getHostName();
     if(ipTest(sip)&&(ssInfo!=" ")){
      InetAddress iip=InetAddress.getByName(sip);
      DatagramPacket dp=new DatagramPacket(buf,0,buf.length,iip,9999);
      ds.send(dp);
      String sInfo=dTime()+"我的信息("+name+"):"+new String(buf,0,dp.getLength());
      pprint(sInfo);
      lst.add(sInfo,0);
     }else if(ssInfo==null){
      lb2.setText("内容格式不能为空!");
     }
    }catch(IOException ee){
     ee.printStackTrace();
    }
     tfInfo.setText(" ");
   }
  });
  new Thread(new Runnable(){
   public void run(){
    while(true){
     try{
      byte[] buf=new byte[1024];
      DatagramPacket dp=new DatagramPacket(buf,buf.length);
      ds.receive(dp);
      String sIP=dp.getAddress().getHostAddress().trim();
      int sPort=dp.getPort();
      String name=dp.getAddress().getHostName();
      String sInfo=dTime()+"来自"+sIP+"("+name+")的信息(端口号:"+sPort+"):"+new String(buf,0,dp.getLength());
      String localIP=InetAddress.getLocalHost().getHostAddress();
      String loopIP="127.0.0.1";
      boolean b1=sIP.equals(localIP);
      boolean b2=sIP.equals(loopIP);
      if((!b1)&&(!b2)){
       lst.add(sInfo,0);
       pprint(sInfo);
       System.out.println(dp.getAddress().getHostName());
      }
     }catch(IOException e){
      e.printStackTrace();
     }
    }
   }
  }).start();
  int delay = 1000; //milliseconds
  ActionListener taskPerformer = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            //...Perform a task...
    
    lb1.setText(dTime());
    //t.setTitle(new Date().toString());
         }
    };
    new javax.swing.Timer(delay, taskPerformer).start();
 }
 String dTime(){
  Date today=new Date();
  SimpleDateFormat sdf=new SimpleDateFormat("hh:mm:ss");
  String time=sdf.format(today);
  return time;
 }
 boolean ipTest(String ip){
  boolean bln=ip.matches("[0-9]{1,3}//.[0-9]{1,3}//.[0-9]{1,3}//.[0-9]{1,3}");
  if(bln){
   lb2.setText("沙舟狼客工作室");
   System.out.println("right");
   return bln;
  }else{
   lb2.setText("IP地址格工不正确!");
   tfIP.setText(" ");
   System.out.println("wrong");
   return bln;
  }
 }
 void pprint(String str){
  try{
   File f=new File("d:/聊天信息.txt");
   FileOutputStream fos=new FileOutputStream(f,true);
   PrintWriter pw=new PrintWriter(fos);
   pw.println(str);
   fos.flush();
   pw.flush();
   fos.close();
   pw.close();
   
  }catch(FileNotFoundException e){
   e.printStackTrace();
  }catch(IOException e){
   e.printStackTrace();
  }
 }
 public static void main(String args[]){
  new Test();
 }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值