-4

私のコードの一部で、サーバーからソケットに書き込み、クライアントからそれを赤くするのを待ちますが、クライアントはサーバーとプログラムブロックから送信したこの整数を決して読み取りません。テストしたところ、サーバーが整数を送信したことがわかりましたが、クライアントが整数を受信しない理由がわかりませんでした。ここにコードを書きました。「// * ** //」のように、「mysize」変数をサーバーからクライアントに転送することに関するコードの重要な部分にコメントしたことに注意してください

ありがとうございました。

私のサーバー部分(重要な行は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();
            }

        }

         }

    }
}

私のクライアントコード:

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


    }

}
4

1 に答える 1

0

writeInt() を呼び出した後、flush() を呼び出します。また、ObjectInputStream の前に ObjectOutputStream を構築する必要があります。

于 2012-08-05T00:15:16.750 に答える