2012-08-05 65 views
-4

在我的代碼的一部分,我從服務器寫入套接字,並等待從客戶端紅色但客戶端永遠不會讀取這個整數,我從服務器和程序塊發送。 我測試,我看到服務器發送的整數,但我cound't找到爲什麼客戶端沒有收到整數。 我在這裏寫了我的代碼。請注意,我評論的代碼,是關於轉讓「mysize」從服務器到客戶端變量一樣重要組成部分「// * ** //」在Java套接字編程中的流塊

謝謝。

我的服務器部分(重要行是行107):

import java.awt.List; 
import java.awt.im.spi.InputMethod; 
import java.io.DataInputStream; 
import java.io.DataOutputStream; 
import java.io.IOException; 
import java.io.ObjectInputStream; 
import java.io.ObjectOutputStream; 
import java.io.OutputStream; 
import java.io.PrintStream; 
import java.net.InetAddress; 
import java.net.ServerSocket; 
import java.net.Socket; 
import java.net.SocketAddress; 
import java.net.UnknownHostException; 
import java.util.ArrayList; 

import javax.swing.JOptionPane; 

/** 
* 
*/ 

/** 
* @author Sina 
* 
*/ 
public class BoxServer { 

    ServerSocket serversocket; 
    static ThreadHandler t[]=new ThreadHandler[1000000]; 
    static int size=0; 
    static ArrayList<Message> messagebox=new ArrayList<Message>(); 
    public static void main(String[] args) { 

     ServerSocket serverSocket = null; 
     try { 
      serverSocket = new ServerSocket(79); 
     } catch (IOException e1) { 
      // TODO Auto-generated catch block 
      System.exit(0); 
      e1.printStackTrace(); 
     } 
     while(true) 
     { 

     try{ 




       //InetAddress inetadress=InetAddress.getLocalHost(); 
       //System.out.println(inetadress); 
       //System.out.println(inetadress.getHostName()); 
       //System.out.println(inetadress.getHostAddress()); 
       Socket socket=serverSocket.accept(); 
       if(socket==null) 
       { 
        System.out.println("null"); 
       } 
       t[size]=new ThreadHandler(socket,size); 
       size++; 
       t[size-1].start(); 



     } 
     catch(UnknownHostException e){ 
     // System.out.println("salam s"); 
      System.exit(0); 
     //System.out.println(e.getMessage()); 
     } 
     catch (IOException e) { 
      System.exit(0); 
     // System.out.println("bye s"); 
      //System.out.println(e.getMessage()); 
     } 


     } 

    } 

} 

class ThreadHandler extends Thread{ 

    private int mysize; 
    Socket mySocket; 
    ObjectInputStream inp; 
    ObjectOutputStream outp; 
    public ThreadHandler(Socket s,int size) 
    { 

     this.mySocket=s; 
     this.mysize=size; 
     System.out.println("Actives: " +Thread.activeCount()); 


    } 
    public void run() 
    { 
     try { 

      inp=new ObjectInputStream(mySocket.getInputStream()); 
      outp=new ObjectOutputStream(mySocket.getOutputStream()); 
      System.out.println("yaaaani minvise ? :|"); 
      outp.writeInt(mysize);//*********// 
      System.out.println(mysize+"neveshte shod dar systam"); 
      System.out.println("age in umad yaaani nevesht"); 
     } catch (IOException e1) { 
      // TODO Auto-generated catch block 
      System.exit(0); 
      e1.printStackTrace(); 
     } 

     while(true) 
     { 
     //System.out.println("thread run"); 
     //System.out.println(mySocket.getLocalPort()); 
     //System.out.println(mySocket.getLocalAddress()); 

     try { 
     // System.out.println("my socket:"+mySocket.getOutputStream()); 
     // System.out.println(mySocket.isConnected()); 
     // System.out.println(inp.available()); 
     // System.out.println("inp = "+inp); 

      if(mySocket.isConnected()) 
      { 


      Message mess=(Message)inp.readObject(); 

     // System.out.print("mess is ====>"); 
     // System.out.println(mess+"  "); 
     // JOptionPane x=new JOptionPane(); 
     // x.setVisible(true); 
     // x.setMessage(mess); 
      //System.out.println("dsd"); 
      //System.out.println("mess: "+mess); 

      if(mess.getReceiver().equals("system-use:code=1")) 
      { 
      // System.out.println("yaroo payamasho mikhad"); 
       String senderOfSystemUse=mess.getSender(); 
       ArrayList<Message> tempInbox=new ArrayList<Message>(); 
       for(int i=0;i<BoxServer.messagebox.size();i++) 
       { 
        if(BoxServer.messagebox.get(i).getReceiver().equals(senderOfSystemUse) && BoxServer.messagebox.get(i).getDeliver()!=true) 
        { 
         tempInbox.add(BoxServer.messagebox.get(i)); 
         BoxServer.messagebox.get(i).delivered(); 
        } 
       } 

      // System.out.println("قاعدتا باید نوشته باشه :دی"); 
       outp.writeObject(tempInbox); 


      } 
      else 
      { 
       //System.out.println("ye payam be sistem ezaf shod :"+mess); 
       BoxServer.messagebox.add(mess); 
      } 

      } 
      //mySocket.close(); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      //System.out.println("bug dar thread"); 
      System.exit(0); 
      //e.printStackTrace(); 
      try { 
       mySocket.close(); 
      } catch (IOException e1) { 
       // TODO Auto-generated catch block 
       System.exit(0); 
      // e1.printStackTrace(); 
      } 

     } 

     } 

    } 
} 

我的客戶端代碼:調用writeInt後

import java.awt.Color; 
import java.awt.GridLayout; 
import java.awt.LayoutManager; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.FocusEvent; 
import java.awt.event.FocusListener; 
import java.io.IOException; 
import java.io.ObjectInputStream; 
import java.io.ObjectOutputStream; 
import java.net.Socket; 
import java.net.UnknownHostException; 
import java.util.ArrayList; 

import javax.swing.ImageIcon; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JTextArea; 
import javax.swing.JTextField; 
import javax.swing.ScrollPaneConstants; 
import javax.swing.SwingUtilities; 

public class Main extends JFrame{ 

    /** 
    * @param args 
    */ 



    public String userTemp; 
    public Main() 
    { 








     this.setDefaultCloseOperation(EXIT_ON_CLOSE); 
     final JPanel jpanel=new JPanel(null); 
     this.getContentPane().add(jpanel); 
     JButton inbox=new JButton("INBOX"); 
     jpanel.add(inbox); 
     inbox.setBounds(0,0,100,30); 
     inbox.setToolTipText("for see your inbox messages click!"); 
     this.setVisible(true); 
     this.setSize(400,400); 
     JLabel receiver=new JLabel("receiver : "); 
     jpanel.add(receiver); 
     receiver.setBounds(0,60,100,30); 
     final JTextField receiverText=new JTextField(); 
     jpanel.add(receiverText); 
     receiverText.setBounds(100,60,100,30); 
     receiverText.setBackground(Color.magenta); 
     JLabel message=new JLabel("message : "); 
     jpanel.add(message); 
     message.setBounds(0, 90, 100, 30); 
     final JTextArea messageText=new JTextArea(); 
     jpanel.add(messageText); 
     messageText.setBounds(100,90,200,30); 
     messageText.setBackground(Color.magenta); 
     ImageIcon x=new ImageIcon("send.png"); 
     JButton send=new JButton(x); 
     jpanel.add(send); 
     send.setBounds(50,130,64,64); 
     final JTextField username=new JTextField("username ..."); 
     JButton signup=new JButton("new user"); 
     signup.setVisible(false); 
     JButton login=new JButton("login Or create"); 
     jpanel.add(login); 
     jpanel.add(signup); 
     jpanel.add(username); 
     username.setBounds(10,240,100,40); 
     login.setBounds(10, 290, 200, 50); 
     signup.setBounds(110, 290, 100, 50); 
     //kpanel 
     final JPanel kpanel=new JPanel(new GridLayout(0, 1)); 
     kpanel.setBackground(Color.green); 
     ImageIcon t=new ImageIcon("back.png"); 
     JButton back=new JButton(t); 
     kpanel.add(back); 
     back.setBounds(0,0,64,64); 
     kpanel.setVisible(false); 
    // this.getContentPane().add(kpanel); 


     try { 

      username.addFocusListener(new FocusListener() { 

       @Override 
       public void focusLost(FocusEvent arg0) { 
        // TODO Auto-generated method stub 

       } 

       @Override 
       public void focusGained(FocusEvent arg0) { 
        // TODO Auto-generated method stub 
        String teString=username.getText(); 
        if(teString.equals("username ...")) 
        { 
         username.setText(""); 
        } 
       } 
      }); 

      final Socket socket = new Socket("127.0.0.1",79); 
      final ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); 
      final ObjectInputStream in=new ObjectInputStream(socket.getInputStream()); 



        try { 
         System.out.println("ghable khundane shomaarash"); 

         int temp=in.readInt();//*********// 

         System.out.println("baade khundane shomaarash"); 

         userTemp=""+temp; 
         login.setText(userTemp); 

         Thread timer=new Thread() 
         { 
          public void run() 
          { 
           while(true) 
           { 
            Message temp=new Message(); 
            temp.setReceiver("system-use:code=1"); 
            temp.setSender(userTemp); 

            try { 
             out.writeObject(temp); 
             sleep(60000); 
            } 
            catch (InterruptedException e) { 
             // TODO: handle exception 
            // e.printStackTrace(); 
            } catch (IOException e) { 
             // TODO Auto-generated catch block 
             //e.printStackTrace(); 
             try { 
              socket.close(); 
             } catch (IOException e1) { 
              // TODO Auto-generated catch block 

             } 
            } 

           } 
          } 
         }; 
         timer.start(); 





        } catch (Exception e1) { 
         // TODO Auto-generated catch block 
         try { 
          socket.close(); 
         } catch (IOException e2) { 
          // TODO Auto-generated catch block 
        //  System.out.println("socket can not close"); 
         } 
        // e1.printStackTrace(); 
        } 












      Thread readerMessagesFromServer=new Thread(){ 

       public void run() 
       { 
        while(true) 
        { 

         try { 
          ArrayList<Message> inboxReceived; 

          inboxReceived = (ArrayList<Message>) in.readObject(); 
         // System.out.println(userTemp+" received in its box :"+inboxReceived.size()); 
          for(int i=0;i<inboxReceived.size();i++) 
          { 
           kpanel.add(new JLabel(inboxReceived.get(i).toString())); 


          } 

         } catch (IOException e) { 
          // TODO Auto-generated catch block 

          try { 

           socket.close(); 
           in.close(); 
           out.close(); 

          } catch (IOException e1) { 
           // TODO Auto-generated catch block 
           e1.printStackTrace(); 
          } 

          e.printStackTrace(); 
         } catch (ClassNotFoundException e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
         } 

        } 
       } 
      }; 

      readerMessagesFromServer.start(); 

      send.addActionListener(new ActionListener() { 

       @Override 
       public void actionPerformed(ActionEvent e) { 

        String rec=receiverText.getText(); 
        String mes=messageText.getText(); 
        String snd=userTemp; 
        Message obj=new Message(); 
        obj.setReceiver(rec); 
        obj.setSender(snd); 
        obj.setText(mes); 

        try { 
         out.writeObject(obj); 
        } catch (IOException e1) { 
         // TODO Auto-generated catch block 
         e1.printStackTrace(); 
        } 

       } 
      }); 

     } catch (UnknownHostException e2) { 
      // TODO Auto-generated catch block 
      e2.printStackTrace(); 
     } catch (IOException e2) { 
      // TODO Auto-generated catch block 
      e2.printStackTrace(); 
     } 



     inbox.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent arg0) { 
       jpanel.setVisible(false); 
       kpanel.setVisible(true); 
       Main.this.getContentPane().add(kpanel); 


      } 
     }); 

     back.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent arg0) { 
       kpanel.setVisible(false); 
       Main.this.getContentPane().remove(kpanel); 
       jpanel.setVisible(true); 

      } 
     }); 




    } 
    public static void main(String[] args) { 



     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       Main ex = new Main(); 
       ex.setVisible(true); 
      } 
     }); 


    } 

} 
+2

請在每個句子的開頭以及單詞I和專名中使用您的shift鍵。閱讀所有小寫字母就像聽別人嘟。。 – 2012-08-05 00:13:39

+1

提示:要獲得更多更快的答案,請提供一些[SSCCE](http://homepage1.nifty.com/algafield/sscce.html)而不是400行代碼。 – Pshemo 2012-08-05 00:19:39

+3

-1這個問題顯示了將問題分解爲幾個相關的代碼行的努力。不歡迎在這裏粘貼代碼 – Bohemian 2012-08-05 00:26:01

回答

0

調用flush()()。你還應該在ObjectInputStream之前構造ObjectOutputStream。

+0

謝謝。現在可以,但是在我沒有使用flush來通過socket進行對象傳輸之前,僅對基元類型或其他一些事物進行刷新? – Sina 2012-08-05 00:36:32

+0

@Sina正確。 'ObjectOutputStream'運行一個內部緩衝區,在writeObject()之後刷新,而不是在寫入原語之後刷新。 – EJP 2012-08-05 08:12:42

+0

很有意思,謝謝 – Sina 2012-08-05 08:19:32