套接字不发送给客户端或客户端未接收

时间:2015-04-05 18:09:53

标签: java android sockets client-server objectinputstream

我有一个Server类和一个在Android设备上运行的Client类。基本上,我需要加载用户的朋友和他们的IP地址。用户的朋友存储在ArrayList中。因此,客户端必须发送朋友的姓名,如果朋友在线或者是" -1,则服务器将使用IP地址进行响应。如果朋友离线服务器可以访问所有用户并将其存储在我定义类型的Arraylist中。我的问题是客户端没有收到IP地址/" -1"从服务器,因此只有一个朋友被检查,因为服务器正在等待响应。客户登录在其他地方完成,并且工作正常。 服务器:

public class Server {
     private static final int port = 9001;
     private static final String IPAddr = "xxx.xxx.xx.10";
     ServerSocket server = null;
     ArrayList <Client> users = new ArrayList<Client>();


     public Server(){
         readUsers();

        try{
            server = new ServerSocket(port);
            System.out.println("connected server on port" + port);
            while(true){
                System.out.println("waiting for connection my ip add is "+ InetAddress.getLocalHost().getHostAddress());
                Socket clientsocket = server.accept();
                System.out.println("Connect to client:"+ clientsocket.getInetAddress().getHostName());
                ClientThread client = new ClientThread(clientsocket);
                client.start();
            }
        } catch(IOException e) {
            System.err.println("Could not listen on port");
        }
     }

     public void readUsers() {
         //read form user text file on start up 
         ReadFile reader = new ReadFile("users.txt");
        try{
         String[] data = reader.OpenFile();
         for (int i = 0 ; i<data.length; i++){
            String[] parts = data[i].split(" ");
            ArrayList<String> ips = new ArrayList<String>();
             for(int j =2; j<parts.length; j++){
                 ips.add(parts[j]);
             }

             Client clnt = new Client(parts[0],parts[1], ips);
              users.add(clnt);
         }
        }catch(Exception e){
            System.err.println("Couldn't read in data");
        }

     }
     public void RegisterUser(){
         //append to user text if a new user registers
     }

//Thread     
    public class ClientThread extends Thread {
        private Socket sckt = null;
        private String purpose;
        ObjectOutputStream objectOutput;
        ObjectInputStream objectInput;

        public ClientThread(Socket sckt){
            super("ClientThread");
            this.sckt = sckt;

        }
        public void run(){
            try{
            objectOutput = new ObjectOutputStream(sckt.getOutputStream());
            objectOutput.flush();
            objectInput = new ObjectInputStream(sckt.getInputStream());
            purpose = objectInput.readUTF();
            if(purpose.contains("login")){
                LoginUser();
            }else {
                LoadClientIP();
            }
            } catch(Exception e){
                System.err.println("Couldnt read purpose: "+ purpose);
            }
        }
        public void LoginUser(){
            try{
                String Username = objectInput.readUTF();
                String Password = objectInput.readUTF();
                int ClientIndex = isClient(Username);
                if (ClientIndex != -1){
                    if(users.get(ClientIndex).password.equals(Password)){
                        //password correct  -> send friends
                        users.get(ClientIndex).online = true;
                        users.get(ClientIndex).SetCurrentIP(sckt.getRemoteSocketAddress().toString());
                        objectOutput.writeUTF("correct");
                        System.out.println(Username + " is correct");
                        LoadClientFriends(Username, ClientIndex);

                        objectOutput.writeObject(users.get(ClientIndex).Friends);
                        System.out.println("Friends sent");
                    } else {
                        //password incorrect -> retry
                        objectOutput.writeUnshared("password");
                        System.out.println(Username + " has wrong password");

                    }
                } else {
                    //not a registered client 
                    objectOutput.writeUTF("wrong");
                    System.out.println(Username + " is not a client");
                }
            } catch(Exception e){
                System.err.println("Couldnt connect to Client socket");
            }
        }
        public void LoadClientIP(){
            try{

            int size = Integer.parseInt(objectInput.readUTF()); //keep track of the number of friends
            System.out.println("The size of friends:"+ size);

            for (int j =0; j<size; j++){
                String client  = objectInput.readUTF();
                System.out.println("Client: "+ client);
                int i = isClient(client);   //index of friend is user arraylist
                if (users.get(i).online == true){
                    String IP_add = users.get(i).IP.get(users.get(i).CurrentIP);
                    objectOutput.writeUTF(IP_add);
                    System.out.println("Client is at index i "+ i + " with IP "+ IP_add);
                }else {
                    objectOutput.writeUTF("-1");
                    System.out.println("Client is not online");
                }

            }
            System.out.println("out of while");
            }catch (Exception e){
                System.err.println("Couldn't load IP");
            }
        }
    }
    public void LoadClientFriends(String name, int index){
        //upon a client signing in, server must load his friends contacts
         ReadFile reader = new ReadFile(name+".txt");
         try{
             String[] data = reader.OpenFile();

             for (int i = 0 ; i<data.length; i++){
                  users.get(index).Friends.add(data[i]);

             }
            }catch(Exception e){
                System.err.println("Couldn't read in friend data");
            }
    }
    public int isClient(String name){
        boolean isclient = false;
        int i =0;
        int index =-1;
        while((isclient == false) && (i<users.size())){
            if (name.equals(users.get(i).Username)){
                isclient = true;
                index = i;
            }else {
                i++;
            }
        }

        return index;
    }
    public static void main(String[] args){
        Server svr = new Server();
    }
}

客户端/ Android:

 public class chat_screen extends ActionBarActivity {
     ArrayList<String> friends;
     ArrayList<String> onlineIP;
     ArrayList<String> onlineFriend;
     private static final int port = 9001;
     private static final String IPAddr = "xx.x.x.4";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_menu);
        friends = (ArrayList<String>) getIntent().getSerializableExtra("Friends");

     Thread FriendThread = new Thread(Connect);
     FriendThread.start();
    }

    //Thread
   Runnable Connect = new Runnable()
   {
       public void run()
       {
        try {
            //Problems: getting stuck when reading in friends, only is able to send the first friend
            Socket connection = new Socket(IPAddr,port);

            ObjectOutputStream objectout = new ObjectOutputStream(connection.getOutputStream());
            objectout.flush();
            ObjectInputStream objectin = new ObjectInputStream(connection.getInputStream()); 

            //send purpose
            objectout.writeUTF("load");
            objectout.flush();
            objectout.writeUTF(Integer.toString(friends.size()));
            objectout.flush();
            //send friends name to get IP
            for(int i =0; i<friends.size(); i++){
                objectout.writeUTF(friends.get(i));
                objectout.flush();
                String ip = objectin.readUTF(); //stuck on this line

                if ((ip.contains("-1"))== false){
                    onlineIP.add(ip);
                    onlineFriend.add(friends.get(i));
                }else {
                   //do nothing
                }
            }
            connection.close();
        }catch (Exception e){
            finish();
        }
     }
    };
}

0 个答案:

没有答案