一个完整的聊天程序

以下程序在jdk1.4.1中调试通过;
OS : Windows XP 
本程序有一个空发消息的处理问题,希望大家多多指教!
mainto:yzmhacke.163.com

客户端的程序:

//Client.java
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*; 
 
 public   class   Client  extends  Frame implements 
  ActionListener,Runnable{
      
      private TextField tf1,tf2;
      private  Label la1,la2;
      private TextArea  ta1,ta2;
      private Socket s;
      private Button b,l;
      private BufferedReader br=null;
      private  PrintWriter pw=null;
         // static  String   port,ip;
      public static void   main(String arg[]) {
         new Client();
      //if(arg[0].length()!=0)  ip=arg[0];
        //if(arg[1].length()!=0)  port=arg[1];
          }
      
      //完成构造函数的说明
      public Client(){
          //完成ip地址与端口的建立
          setLayout(new GridLayout(6,1));
         Panel panel=new Panel();      
          tf1=new TextField(20);
          tf2=new TextField(10);
          la1=new Label("IP地址 ");
           
          la2=new Label("对应端口    ");
          Button l=new Button("连接");
          l.setBackground(Color.green);
          //l.addActionListener(this);
          panel.add(la1);
          panel.add(tf1);
          panel.add(la2);
          panel.add(tf2);
          panel.add(l);
          add(panel);
        
        //输入框与显示框
        
         ta1=new  TextArea(100,300);
        
         add(new Label("消息框"));
         
         add(ta1);
         add(new Label("用户输入框"));
         ta2=new  TextArea(30,300);          
           
           add(ta2);
          Panel p2=new Panel();
          b=new Button("发送"); 
          b.setBackground(Color.yellow);
          p2.add(b);
          add(p2);
          setTitle("客户端");
          setSize(300,450);
          setResizable(false);
          setVisible(true);
          //捕获各种的异常 
          l.addActionListener(this);   
      //    b.addActionListener(this);
          //增加了一个关闭的事件
          addWindowListener(new WindowAdapter(){
               
          public void windowClosing(WindowEvent exit){ System.exit(0);}});
         Thread   ThreadReader=new Thread(this);
           
          ThreadReader.start();
          
        b.addActionListener(this);             
        
          
 } 
           
 public void run(){
                   while(true){
               try{
                   ta1.append("/n #_____________________________#/n"+br.readLine());
             }catch(Exception exo){} 
             }    
      }
      
        //客户向服务端发送消息啊!
    
 
 
 public void actionPerformed(ActionEvent  e)
   {   String command=e.getActionCommand();
        
        if("发送".equals(command)) 
         {  
           if(ta2.getText().trim()!=null)
              {   
                ta1.append("/n  客户端的消息:/n"+ta2.getText());
                pw.println(ta2.getText()+"/n");//" /n   客户短信: /n "
                }   
            else 
                    if(ta2.getText().trim()==null)
            { ta1.append("请输入完整的IP地址与端口以及、/n"+"不能空发消息");}   
                     
         
                   ta2.setText(" "); //结束的时候清空文本框
          }
     else 
       if("连接".equals(command)){
                
       try
           {
             
           //借助连接的按钮完成远程pc的连接的工作。建立输入与输出流两个工具
         s=new Socket(tf1.getText().toString(),Integer.parseInt((tf2.getText()).trim()));
         //Integer.parseInt((tf2.getText()).trim())
         br=new BufferedReader(new InputStreamReader(s.getInputStream()));
         pw=new PrintWriter(s.getOutputStream(),true);
         //ta1.append("/n 服务端来消息:/n"+br.readLine());
         }
         catch(Exception ex){
             //ta1.append("产生了输入输出异常无法完成交互!");
             }
            
          }           
                 
       }   
                             
    
  }   


/*******************服务端的程序*************************/
//Server.java
package server;
import java.io.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;

public class  Server{
    public static void main(String arg[]){
         ServerService MyServer=new ServerService(8000,10);    
         
   }
  }
 //交互端的服务窗口    
  class ServiceThread extends Frame 
  implements  ActionListener,Runnable{
         ServerService FatherListener;
         Socket ConnectedClient;
       Thread   ConnectedThread;
       Panel   ListenePanel;
       TextArea   ServerMeg; 
       TextArea  ServerWrite;
       Label  la;  
       Button bt; 
       BufferedReader in;
       PrintWriter out;    
      public ServiceThread(ServerService  sv,Socket s){
                    //容器与格子组建的结合
                    
                     FatherListener=sv;
                     ConnectedClient=s;
                     ConnectedThread =new Thread(this);
                     //采用线程的目的是利用他的并发机制,实现多个任务
                     
                     //在当前的类中(this)通过Runnabel()接口实现Thread()的Run()方案
                     
                     
                     setTitle("Answer Client");
                     setLayout(new GridLayout(4,1));
                     //采用格子组建的形式完成组建的安排 
                     
                     ServerMeg=new TextArea(null,5,45,TextArea.SCROLLBARS_VERTICAL_ONLY);
                     //添加各种组建到容器当中
                     ListenePanel=new Panel();
                     ListenePanel.add(ServerMeg);
                     add(ListenePanel);
                     addWindowListener(new WindowAdapter(){
                          public void windowClosing(WindowEvent e){
                           //((Frame)e.getWindow()).dispose();//保留的语句
                              System.exit(0);
                              }});
                     //第二个Panel() 
                     
                    la=new Label("服务端消息输入框...............");
                    add(la);
                    ServerWrite=new TextArea(10,50);
                    add(ServerWrite);
                     //add(p2);
                     setSize(355,360);
                     
                     Panel p3=new Panel();
                     
                     bt=new Button("传送"); 
                     bt.addActionListener(this);
                     p3.add(bt);
                     add(p3);
                   
                     setResizable(false);
                     
                     show();
                     InetAddress ClientAddress=ConnectedClient.getInetAddress();
                     ServerMeg.append("Client Conneted from /n "+ClientAddress.getHostAddress()+"!");
                     
                     }
                  //完成事件的部
             //面临的一个问题是空发消息
             
              public void  actionPerformed(ActionEvent ex){
                  
                      if(ex.getSource()==bt){
                             if((int)((ServerWrite.getText().toString()).length())!=0)
                               ServerMeg.append("服务端消息:"+ServerWrite.getText()+"/n");
                               out.println("/n"+ServerWrite.getText());  
                             ServerWrite.setText("");
                       }
                      else {
                          
                               ServerMeg.append("系统提示: 不能空法消息!/n");
                          
                          }                          
                  
                  }    
                  
                      
                                     
         //  覆盖线程的run()方法
         
          public void run(){
              
            try{
                    in=
                  new  BufferedReader(new InputStreamReader(ConnectedClient.getInputStream())); 
                   out=new PrintWriter(ConnectedClient.getOutputStream(),true);
                
                out.println("Hello!    Wellocme  connect  our server !"); 
                
                out.flush();
                String s=in.readLine();
                if(s.equals("bye"))
                    out.println("已经断开与服务器的连接.............. /n   欢 迎 下 次 观 顾!");
                while(!s.equals("bye")){
                     ServerMeg.append("/n#_________________________________________#/n"+s);
                    s=in.readLine();
                    }
                 
              
                     
                ConnectedClient.close(); 
                   
              }catch(Exception e){}
               FatherListener.addMeg("Client"+"Cloesd."+"/n");    
           
          }//run(),finished;
      
      }    
        
  //服务窗口
  class ServerService extends Frame{
        ServerSocket Listener;
        TextArea ListenerMeg;
        public ServerService(int port,int Count){
              try{
                  
                   Listener=new ServerSocket(port,Count);//开启监听的端口
                   
                   setTitle("服务监听");
                   this.addWindowListener(new WindowAdapter(){
                        public void windowClosing(WindowEvent e){
                            ((Frame)e.getWindow()).dispose();//释放组建与内存
                           System.exit(0);           
                            
                            }});
                            setLayout(new BorderLayout());
                            ListenerMeg=new TextArea("监听服务已经启动 /n",10,50);
                            add("Center",ListenerMeg);
                            setResizable(false);//设计固定的状态
                            pack();//重新的打包
                            
                            show();
                            while(true){
                                Socket connected=Listener.accept();//等待外部的连接,直到连接成功才返回一个套接字
                                
                                InetAddress ClientAddress=connected.getInetAddress();
                                ListenerMeg.append("/n Client connected from :/n"+ ClientAddress.toString());
                                ServiceThread MyST=new ServiceThread(this,connected);//初使化服务线程
                                //this指向当前对象的指针
                                
                                MyST.ConnectedThread.start();//启动线程
                             }    //获取套接子,激活线程,采用循环的语句解决方式
                             
                             
                           }catch(Exception ep){}
                           
                       }
                  public void addMeg(String s){
                      ListenerMeg.append(s);
                      
                      }     
                 }        
阅读更多
上一篇点灯小游戏
下一篇 一个必看的Java程序
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭