当然,用java,只需要源代码,最好能用jdk可以调试的,我认为“实验2  模拟客户机服务器通信”,比较简单,只要做一个客户服务器聊天的程序就好。谁有代码,请贴一下好吗?所列的其他实验的代码也行。

解决方案 »

  1.   

    实验1  TCP/IP协议包分析
    实验2  模拟客户机服务器通信
    实验3  模拟Ping的功能实现
    实验4  模拟FTP服务
    实验5  模拟网络流量控制任选一题的代码贴出来源代码,谢谢。
      

  2.   

    还要什么流量分析?tcp包捕获?java没办法吧。
      

  3.   

    ChatClient.javapackage chatroom;import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import javax.swing.*;public class ChatClient extends Frame implements ActionListener{
    Label label1=new Label("聊天");
    Panel panel=new Panel();
    TextField tf=new TextField(10);
    TextArea ta=new TextArea();
    ServerSocket server;
    Socket client;
        protected PrintWriter m_Out;
        protected BufferedReader m_In;
        String m_szName="";

    public ChatClient(String name){
    super("客户机");
            this.m_szName =name;
    setSize(250,250);
    panel.add(label1);
    panel.add(tf);
    tf.addActionListener(this);
    add("North",panel);
    add("Center",ta);
    addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e){
                    ChatClient.this.m_Out .write("Byebye Everyone!");
    System.exit(0);}});
    show();
            this.m_szName=JOptionPane.showInputDialog(null,"Name");//swing,awt
            this.setTitle(this.m_szName) ;
    try{
    client=new Socket(InetAddress.getLocalHost(),5000);
    ta.append("已连接的服务器:"+client.getInetAddress().getHostAddress()+"\n\n");
                this.m_In=new BufferedReader(new InputStreamReader(client.getInputStream()));
                this.m_Out=new PrintWriter(client.getOutputStream());             
                this.m_Out.println(this.getName());
                this.m_Out.flush() ;
    }
    catch(IOException ioe){}        
            String line="";
    while(true){
    try{
    line=this.m_In.readLine();
    ta.append("服务器说:"+line+"\n");
    }catch(IOException e){}
    }
    }
    public void actionPerformed(ActionEvent e){
            String str=tf.getText();
            this.m_Out.println(str) ;
            this.m_Out.flush();
            tf.setText("");
            ta.append("我说:"+str);
            ta.append("\n");
    }
        
        public String getName() {
            return m_szName;
        }
        
        public void setName(String m_szName) {
            this.m_szName = m_szName;
        }
        
    public static void main(String args[]){
    new ChatClient("abs");
    }
    }
      

  4.   

    ChatServer.javapackage chatroom;import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.util.*;public class ChatServer extends Frame implements ActionListener{
    Label label1=new Label("聊天");
    Panel panel=new Panel();
    TextField tf=new TextField(10);
    TextArea ta=new TextArea();
    ServerSocket server;
    Socket client;
    InputStream in;
    OutputStream out;
        Vector m_vCustomsOnLine=new Vector();//客户管理

        /**
         * 构造函数
         */
    public ChatServer(){
    super("服务器");//标题
    setSize(250,250);
    panel.add(label1);
    panel.add(tf);
    tf.addActionListener(this);//监听
    add("North",panel);
    add("Center",ta);
            
            //退出程序
    addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e){
    System.exit(0);}});
            
    show();
            
    try{//捕获异常
    server=new ServerSocket(5000);//port
                while(true){//进行多个客户的接收
                    client=server.accept();                
                    CustomThread ct=new CustomThread(this,client);//创建服务线程
                    this.m_vCustomsOnLine.addElement(ct);                
                    ct.start();//启动服务线程
                }
    }
    catch(IOException ioe){}
    }
        
    public void actionPerformed(ActionEvent e){
            String str=tf.getText();
            Enumeration enum=this.m_vCustomsOnLine.elements() ;
            while (enum.hasMoreElements()) {
                ((CustomThread)enum.nextElement()).write2Client(str);//强制转换
            }
            ta.append("我说:"+str+"\n");
            tf.setText("");
    } public void appendMessage(String msg){
    this.ta.append(msg);
    } public static void main(String args[]){
    new ChatServer();
    }
    }
    /**
     *
     *一个用户的线程
     */
      class CustomThread extends Thread{
            protected Socket m_Client;
            String m_szLine;//读取一行数据
            String m_szCustomName;//用户名字        protected PrintWriter m_Out;
            protected BufferedReader m_In;
            protected ChatServer m_Server;//服务器                /**
             * 构造函数
             * @param group 线程组
             * @param server 服务器线程
             * @param client 客户接口
             */
            CustomThread(ChatServer server,Socket client){
                  this.m_Server=server;
                  this.m_Client =client;
                  try{
                        this.m_In=new BufferedReader(new InputStreamReader(this.m_Client.getInputStream()));
                        this.m_Out=new PrintWriter(this.m_Client.getOutputStream());              
      }catch(IOException e){
                        try{
                              this.m_Client.close() ;
                        }catch(IOException e1){
                              System.err.println("有问题"+e1);
                              return;
                        }
                  }
                  this.m_szCustomName="";     
                    try {
                        this.m_szCustomName =this.m_In.readLine();                                        
                    }
                    catch (IOException ex) {
                        System.err.println("Read Client name error!");
                    }
                    this.m_Server.appendMessage("已连接的"+this.m_szCustomName+"\n");
            }        /**
             * 获取用户名字
             * @return 用户名字
             */
            public String getCustomName(){
                  return this.m_szCustomName ;
            }        /**
             * 设置用户名字
             * @param szCustomName 用户名字
             */
            public void setCustomName(String szCustomName){
                  this.m_szCustomName=szCustomName ;
            }        /**
             * 获取客户接口
             * @return 接口
             */
            public Socket getSocket(){
                  return this.m_Client;
            } public void run(){         
              String line="";
              try{
                    while(true){
                          line=this.m_In.readLine();//读取
             
                          this.m_Server .appendMessage(this.m_szCustomName+"说:"+line+"\n") ;
                    }
              }catch(IOException e){
              }catch(NullPointerException e){
              }
            }
            
            public void write2Client(String msg){
                this.m_Out.println(msg) ;
                this.m_Out.flush() ;
            }
      }
      

  5.   

    compile.bat
    javac *.java -d .runClient.bat
    E:\application\j2sdk1.4.0\bin\java.exe -classpath . chatroom.ChatClientrunServer.bat
    E:\application\j2sdk1.4.0\bin\java.exe -classpath . chatroom.ChatServer这个程序够简单吧,这是帮我同学做的例子。你看看吧!
      

  6.   

    试验题目说了,都是模拟。所以,应该能做出来。
    非常感谢 newman0708(nch) ,我会仔细研究一下。
    如果还有人会其他的试验题目,请跟贴。
    明晚结贴。
      

  7.   

    /**这不是我写的,是Oreilly出的"java经典实例,经过修改可以实现,相对完全点,希望对你有帮助啦*/
    //聊天室的客户端  ChatClient
    import java.applet.*;
    import java.awt.*;
    import java.io.*;
    import java.net.*;
    import java.awt.event.*;public class ChatClient extends Applet{
       protected boolean loggedIn;//登入状态
       protected Frame cp;//聊天室框架
       protected static int PORTNUM=7777; //缺省端口号7777
       protected int port;//实际端口号
       protected Socket sock;
       protected BufferedReader is;//用于从sock读取数据的BufferedReader
       protected PrintWriter pw;//用于向sock写入数据的PrintWriter
       protected TextField tf;//用于输入的TextField
       protected TextArea ta;//用于显示对话的TextArea
       protected Button lib;//登入按钮
       protected Button lob;//登出的按钮
       final static String TITLE ="Chatroom applet>>>>>>>>>>>>>>>>>>>>>>>>";
       protected String paintMessage;//发表的消息
       public ChatParameter Chat; 
       
       public void init(){
        paintMessage="正在生成聊天窗口";
        repaint();
        cp=new Frame(TITLE);
        cp.setLayout(new BorderLayout());
        String portNum=getParameter("port");//呢个参数勿太明
        port=PORTNUM;
        if (portNum!=null)  //书上是portNum==null,十分有问题
           port=Integer.parseInt(portNum);
           
        //CGI
       
        ta=new TextArea(14,80);
        ta.setEditable(false);//read only attribute
        ta.setFont(new Font("Monospaced",Font.PLAIN,11));
        cp.add(BorderLayout.NORTH,ta);
       
        Panel p=new Panel();
        Button b;
       
        //for login button
        p.add(lib=new Button("Login"));
        lib.setEnabled(true);
        lib.requestFocus();
        lib.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e){
        login();
        lib.setEnabled(false);
        lob.setEnabled(true);
        tf.requestFocus();//将键盘输入锁定再右边的文本框中
        }
        });
       
        //for logout button
        p.add(lob=new Button ("Logout"));
        lob.setEnabled(false);
        lob.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
        logout();
        lib.setEnabled(true);
        lob.setEnabled(false);
        lib.requestFocus();
        }
        });
       
       
        p.add(new Label ("输入消息:"));
        tf=new TextField(40);
        tf.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
        if(loggedIn){
        //pw.println(Chat.CMD_BCAST+tf.getText());//Chat.CMD....是咩野来?
        int j=tf.getText().indexOf(":");
        if(j>0) pw.println(Chat.CMD_MESG+tf.getText());
       
        else
        pw.println(Chat.CMD_BCAST+tf.getText());
        tf.setText("");//勿使用flush()?
        }
        } 
        });
       
        p.add(tf);
        cp.add(BorderLayout.SOUTH,p);
         
        cp.addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent e){
        //如果执行了setVisible或者dispose,关闭窗口
        ChatClient.this.cp.setVisible(false);
        ChatClient.this.cp.dispose();
        logout();
        }
        });
       
        cp.pack();//勿明白有咩用?
        //将Frame cp放在中间
        Dimension us=cp.getSize(),
         them=Toolkit.getDefaultToolkit().getScreenSize();
         int newX=(them.width-us.width)/2;
         int newY=(them.height-us.height)/2;
         cp.setLocation(newX,newY);
         cp.setVisible(true);
         paintMessage="Window should now be visible";
         repaint();
         
         }
         
         
         
      //登录聊天室
      public void login(){
       if(loggedIn)   return;
      
       try{
          sock=new Socket(getCodeBase().getHost(),port);
          is=new BufferedReader(new InputStreamReader(sock.getInputStream()));
          pw=new PrintWriter(sock.getOutputStream(),true);
          }catch(IOException e){
           showStatus("Can't get socket: "+e);
           cp.add(new Label("Can't get socket: "+e));
           return;}
          
        //构造并且启动读入器,从服务器读取数据,输出到文本框中
        //这里,长成一个线程来避免锁住资源(lockups)  
        new Thread (new Runnable(){
         public void run(){
         String line;
         try{
           while(loggedIn &&((line=is.readLine())!=null))
             ta.appendText(line+"\n");
             }catch(IOException e){
              showStatus("我的天啊,掉线了也!!!!");
              return;
              }
                               }
                      }).start();
                      
                      
               //假定登录(其实只是打印相关信息,并没有真正登录)
              // pw.println(Chat.CMD_LOGIN+"AppletUser");
              pw.println(Chat.CMD_LOGIN+"AppletUser");
               loggedIn =true;      
          
         }   
         
         
      //模仿退出的代码
      public void logout(){
       if(!loggedIn)
          return;
          
          loggedIn=false;
          try{
             if(sock!=null)
                sock.close();     
          }catch(IOException ign){
           // 异常处理
           }
      
      }      
       public void paint(Graphics g){
        Dimension d=getSize();
        int h=d.height;
        int w=d.width;
        g.fillRect(0,0,w,2);
        g.setColor(Color.black);
        g.drawString(paintMessage,10,(h/2)-5);
       
        }
       
       
    }
      

  8.   

    //简单的聊天室服务器端
    import java.net.*;
    import java.io.*;
    import java.util.*;public class ChatServer{
       //聊天室管理员ID
       protected final static String CHATMASTER_ID="ChatMaster";
       //系统信息的分隔符
       protected final static String SEP=": ";
       //服务器的Socket
       protected ServerSocket  servSock;
       //当前客户端列表
       protected ArrayList clients;
       //调试标记
       protected boolean DEBUG=false;
       public ChatParameter Chat;
       
       //主方法构造一个ChatServer,没有返回值
       public static void main(String[] argv){
        System.out.println("Chat server0.1 starting>>>>>>>>>>>>>>>>");
        ChatServer w=new ChatServer();
        w.runServer();
        System.out.println("***ERROR*** Chat server0.1 quitting");
         
          }
          
          
       //构造和运行一个聊天服务
       ChatServer(){
        Chat=new ChatParameter();
        clients=new ArrayList();
        try{
           servSock=new ServerSocket(7777);//实有问题拉,不过可能是他自己定义既一个class.
           System.out.println("Chat Server0.1 listening on port:"+7777);
           }catch(Exception e){
            log("IO Exception in ChatServer.<init>");
            System.exit(0);
             }
                 }
                 
        public void runServer(){
         try{
            while(true){
             Socket us=servSock.accept();
             String hostName=us.getInetAddress().getHostName();
             System.out.println("Accpeted from "+hostName);
             //一个处理的线程
             ChatHandler cl=new ChatHandler(us,hostName);
             synchronized(clients){
             clients.add(cl);
             cl.start();
             if(clients.size()==1)
                cl.send(CHATMASTER_ID,"Welcome!You are the first one here");
              else{
                cl.send(CHATMASTER_ID,"Welcome!You are the latest of"+
                   clients.size()+" users.");
                   }  
              }
              }
         }catch(Exception e){
         log("IO Exception in runServer:"+e);
         System.exit(0);
         }
         }
        
        
        protected void log(String s){
         System.out.println(s);
         }
        
        
         //处理会话的内部的类
         protected class ChatHandler extends Thread {
          //客户端scoket
          protected Socket clientSock;
          //读取socket的BufferedReader
          protected BufferedReader is ;
          //在socket 上发送信息行的PrintWriter
          protected PrintWriter pw;
          //客户端出主机
          protected String clientIP;
          //句柄
          protected String login;
         
          public ChatHandler (Socket sock,String clnt)throws IOException {
          clientSock=sock;
          clientIP=clnt;
          is=new BufferedReader(
               new InputStreamReader(sock.getInputStream()));
           pw=new PrintWriter (sock.getOutputStream(),true);  
         
          }
         
            //每一个ChatHandler是一个线程,下面的是他的run()方法
            //用于处理会话
            public void run(){
             String line;
            
             try{
                while((line=is.readLine())!=null){
                 char c=line.charAt(0);//我顶你老母啊 ,果只Chat.CMD咩xx冇定义 扑啊///!!!
                 line=line.substring(1);
                 switch(c){
                 //case Chat.CMD_LOGIN:
                 case 'l':
                      if(!Chat.isValidLoginName(line)){
                       send(CHATMASTER_ID,"LOGIN"+line+"invalid");
                       log("LOGIN INVALID from:"+clientIP);
                       continue;
                       }
                      
                       login=line;
                       broadcast(CHATMASTER_ID,login+" joins us,for a total of"+
                                  clients.size()+" users");
                       break;
                      
                 // case Chat.CMD_MESG:
                 case 'm':
                     if(login==null){
                      send(CHATMASTER_ID,"please login first");
                      continue;
                      }
                     
                      int where =line.indexOf(Chat.SEPARATOR);
                      String recip=line.substring(0,where);
                      String mesg=line.substring (where+1);
                      log("MESG: "+login+"--->"+recip+": "+mesg);
                      ChatHandler cl=lookup(recip);
                      if(cl==null)
                         psend(CHATMASTER_ID,recip+"not logged in.");
                      else
                         cl.psend(login,mesg);
                         
                     break;
                     
                     
                   //case Chat.CMD_QUIT:
                   case 'q':
                     broadcast(CHATMASTER_ID,"Goodbye to "+login+"@"+clientIP);
                     close();
                     return;//ChatHandler结束
                     
                     
                  // case Chat.CMD_BCAST:
                  case 'b':
                       if(login!=null)
                          broadcast(login,line);
                       else
                          log("B<L FROM"+clientIP);
                        break;
                        
                    default:
                        log("Unknow cmd"+c+"from"+login+"@"+clientIP);
                             }
                        }
                         }catch(IOException e){
                          log("IO Exception :"+e);
                          }finally{
                             //sock 结束,我们完成了
                             //还不能发送再见的消息
                             //得有简单的基于命令的协议才行
                             System.out.println(login+SEP+"All Done");
                             synchronized(clients){
                              clients.remove(this);
                              if(clients.size()==0){
                              System.out.println(CHATMASTER_ID+SEP+
                                       "I'm so lonely I could cry>>>>>");
                                  }else if(clients.size()==1){
                                   ChatHandler last=(ChatHandler)clients.get(0);
                                   last.send(CHATMASTER_ID,"Hey,you are talking to yourself again");
                                   }
                                   else{
                                   broadcast(CHATMASTER_ID,"There are now"+clients.size()+" users");
                                   }
                              }
                           }
                        }
         
         
         
         
          protected void close(){
          if(clientSock==null){
          log("close when not open");
          return;
          }
          try{
            clientSock.close();
            clientSock=null;
            }catch(IOException e){
             log("Failure during close to "+clientIP);
             }
          }
         
         
          //发送一条消息给用户
          public void send(String sender,String mesg){
          pw.println(sender+SEP+"*>"+mesg);
          }
         
          //发送私有的消息
          protected void psend(String sender ,String msg){
          send("<*"+sender+"*>",msg);
          }
         
         
         
          //发送一条消息给所有的用户
          public void broadcast (String sender,String mesg){
          System.out.println("Broadcasting"+sender+SEP+mesg);
          for(int i=0;i<clients.size();i++){
          ChatHandler sib=(ChatHandler)clients.get(i);
          if(DEBUG)
             System.out.println("Sending to"+sib);
          sib.send(sender,mesg);
                      }
                   
                   if(DEBUG) System.out.println("Done broadcast");
               }
               
               
           protected ChatHandler lookup(String nick){
            synchronized(clients){
            for(int i=0;i<clients.size();i++){
            ChatHandler cl=(ChatHandler)clients.get(i);
            if(cl.login.equals(nick))
            return cl;
            }
                            }
                      return null;      
               } 
                  
               
          //将ChatHandler对象转换成一个字符串
          public String toString(){
           return "ChatHandler["+login+"]";
           }
         
         
          }              
    }
      

  9.   

    //solve the problem Chat.CMD.....这是参数public class ChatParameter {
    public static final char CMD_BCAST='b';
    public static final char CMD_LOGIN='l';
    public static final char CMD_MESG='m';
    public static final char CMD_QUIT='q';
    public static final char SEPARATOR=':';//?????
    public static final int PORTNUM=7777;

    public boolean isValidLoginName(String line){
    if (line.equals("CHATMASTER_ID"))
       return false;
     return true;  
    }


    public void main(String[] argv){
    }  
    }