天天看點

聊天室功能實作代碼



功能子產品設計

發送端打包發送:

public  chat() throwsSocketException{

        dp=new DatagramPacket(buf, buf.length);

    ds=new DatagramSocket(3000);

    thread =newThread(new Runnable()//定義一個匿名内部類,執行個體化Runnable對象的同時,建立線程 

        {    

             //重寫run()

            public void run() {              

                while (true) {  

                    try { 

                        ds.receive(dp);//接收發送端的資料 

                        String str = new String(dp.getData(), 0, dp.getLength());//讀出發送端發送的有效長度 

                        area.setText(area.getText()+"\n"+dp.getAddress().getHostAddress()+ " say:" + str);//客戶機對本機說的話,以字元串顯示出來  

                    } catch(IOException e) {  

                        e.printStackTrace();  

                    }  

                }  

            }  

        });

 }

内部類監聽,将資料寫入檔案:

classTlisttener implements ActionListener {

        public void actionPerformed(ActionEvent e) {

            Filefile = new File("d:/s.txt");

            FileOutputStreamout = null;

            try {

                out = newFileOutputStream(file, true);

            } catch (FileNotFoundException e1) {

                e1.printStackTrace();

            }

            Strings = txt.getText().trim();

            byte a[] = s.getBytes();   

            try {

                out.write(a);

            } catch (IOException e1) {

                e1.printStackTrace();

            }

            area.setText(area.getText() + "\r\n"+ s);

            try {  

                dp= new DatagramPacket(a, a.length,InetAddress.getByName(ip.getText()), 3001);//擷取目标位址和端口号

                ds.send(dp);//發送  

            } catch (UnknownHostException e1) {  

               e1.printStackTrace();  

            } catch (IOException e1) {  

               e1.printStackTrace();  

            }  

           ((TextField) e.getSource()).setText("");

//清空 

        }

    }

界面布局:

public void createFrame() {

        setLocation(700, 300);

        setSize(300, 500);

        buto.setSize(100, 40);

        add(txt,BorderLayout.CENTER);

        add(area,BorderLayout.NORTH);

        add(ip,BorderLayout.WEST);

        add(buto,BorderLayout.EAST);

        ip.setText("127.0.0.1");

        pack();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        txt.addActionListener(new Tlisttener());//監聽文本域

        buto.addActionListener(new Tlisttener());//對按鈕進行監聽

        setVisible(true);