简易的聊天编程代码(还没有加入多线程)

public class UDPSender {
    
    File file = null;
    
    /**
     * 构造器
     * @throws IOException
     */
    public UDPSender() throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String fname = sdf.format(new Date())+"txt";
        file = new File(fname);
        if(!file.exists()){
            file.createNewFile();
        }
    }
    
    public void start() throws IOException{
        
        String ip = "192.168.4.189";
        DatagramSocket ds = new DatagramSocket(5789);
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        //文件打印流
        PrintWriter pw = new PrintWriter(new FileOutputStream(file),true);
        //目前不能写死,要根据数组的真实长度来操作
        DatagramPacket dp = null;
        byte[] b = null;
        String msg = "";
        while(!(msg=br.readLine()).equals("quit")){
            //将数据的字节数存储到byte数组中
            b = msg.getBytes();
            dp = new DatagramPacket(b,0,b.length,InetAddress.getByName(ip),5789);
            ds.send(dp);
            pw.println("【"+DateFormat.getDateTimeInstance().format(new Date())+"】"+"我:"+msg);
            
            //在接收数据之前,重新new一个dp对象,并未byte数组赋一个更大的值,防止数据丢失
            dp = new DatagramPacket(new byte[128], 128);
            
            ds.receive(dp);
            msg = new String(dp.getData());
            System.out.println("鞍山:"+msg);
            //生成当前系统时间
            pw.println("【"+DateFormat.getDateTimeInstance().format(new Date())+"】"+"鞍山:"+msg);
        }
        pw.close();
        br.close();
        ds.close();
    }
    
    public static void main(String[] args) throws IOException {
        new UDPSender().start();
        
    }
}

猜你喜欢

转载自blog.csdn.net/sinat_42698442/article/details/81269463
今日推荐