聊天室功能实现代码

来源:互联网 发布:python数据分析 编辑:程序博客网 时间:2024/05/16 02:55


功能模块设计

发送端打包发送:

public chat() throwsSocketException{

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

   ds=new DatagramSocket(3000);

   thread =newThread(new Runnable()//定义一个匿名内部类,实例化Runnable对象的同时,创建线程 

       {    

            //重写run()

           publicvoid 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();  

                   }  

               }  

           }  

       });

 }

内部类监听,将数据写入文件:

classTlisttenerimplements ActionListener {

 

       publicvoid 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("");

//清空 

 

       }

 

   }

界面布局:

publicvoid 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);

0 0
原创粉丝点击