简体   繁体   中英

Can't get sockets' DataOutputStream in loop for sockets list

I am trying to create a client/server program with Java where clients send simple string to server and each client connected to server gets this String. So I created 2 server classes for server which create new thread for each client and listen to them. Also there is a List of client sockets. I want to use it to send to each client the String which was sent by one of clients. I use foreach loop for that. But I got the Dataoutputstream only for the client which sent the String to server:

public void run(){
    try{
        while(true){
            String data = in.readUTF();
            for(Socket soc : GlobalQdaServer.allClients){
                DataOutputStream sOut = new DataOutputStream(soc.getOutputStream());
                sOut.writeUTF(data + ". Total clients number in list: " + GlobalQdaServer.allClients.size());
            }                
        }
    }
    catch(EOFException ex){
        System.out.println(ex.getMessage());
    } 
    catch(IOException ex){
        System.out.println(ex.getMessage());
    } 
}

So, only this client recieves the String (which it sent itself). Other recieve nothing. These are full classes:

    import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.*;
import java.util.ArrayList;
import java.util.List;


public class GlobalQdaServer {
    public static List<Socket> allClients = new ArrayList<Socket>();

    public static void main(String[] args) {
        try{
            int serverPort = 7896;
            ServerSocket listenSocket = new ServerSocket(serverPort);
            while(true){
                Socket clientSocket = listenSocket.accept();
                allClients.add(clientSocket);
                Connection c = new Connection(clientSocket);
            }
        }
        catch(IOException ex){
            System.out.println("Server Socket creating failiure");            
        }
    }

}

class Connection extends Thread{
    DataInputStream in;
    DataOutputStream out;
    Socket clientSocket;
    public Connection(Socket aClientSocket){
        try{
            clientSocket = aClientSocket;
            in = new DataInputStream(clientSocket.getInputStream());
            out = new DataOutputStream(clientSocket.getOutputStream());
            this.start();
        }
        catch(IOException ex){
            System.out.println(ex.getMessage());
        }        
    }

    public void run(){
        try{
            while(true){
                String data = in.readUTF();
                for(Socket soc : GlobalQdaServer.allClients){
                    DataOutputStream sOut = new DataOutputStream(soc.getOutputStream());
                    sOut.writeUTF(data + ". Total clients number in list: " + GlobalQdaServer.allClients.size());
                }                
            }
        }
        catch(EOFException ex){
            System.out.println(ex.getMessage());
        } 
        catch(IOException ex){
            System.out.println(ex.getMessage());
        } 
    }
}


    import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;


public class GlobalQdaClient {

    public static void main(String[] args) throws IOException {
        int serverPort = 7896;
        Socket s = new Socket("localhost", serverPort);
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String input = "";
        while(!input.equals("end")){
            input = reader.readLine();
            try{
                DataInputStream in = new DataInputStream(s.getInputStream());
                DataOutputStream out = new DataOutputStream(s.getOutputStream());
                out.writeUTF(input);
                String data = in.readUTF();
                System.out.println("Recieved this: " + data);            
            }
            catch(UnknownHostException ex){
                System.out.println(ex.getMessage());
            }
            catch(EOFException ex){
                System.out.println(ex.getMessage());
            }
            catch(IOException ex){
                System.out.println(ex.getMessage());
            }
        }
    }    
}

Please, help to find the course of problem. I am new to sockets. Thank you

Your Program Actually works fine.

The only problem is that you're blocking the clients with continuos reads.

So you will actually see the message you sent on other clients after they unblock from reading.

Try The following :

  • Run Server
  • Run Client1
  • Run Client2
  • Send Message From Client1 ( Note That Client2 is now blocked because of input)
  • Send Message From Client2

Now you'll see the Message that sent previously from client1 on client2.

But If you need both clients to receive the messages once it's sent you need to create another thread to fetch the updates continuously.

I've modified your client to do so.

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;


public class GlobalQdaClient extends Thread {
        int serverPort = 7896;
        BufferedReader reader ;
        static String input = "";
        Socket s;
        DataInputStream in ;
        DataOutputStream out ;
public GlobalQdaClient() {
        try {
            reader  = new BufferedReader(new InputStreamReader(System.in));
             s = new Socket("localhost", serverPort);
             in = new DataInputStream(s.getInputStream());
             out = new DataOutputStream(s.getOutputStream());
        } catch (IOException ex) {
            Logger.getLogger(GlobalQdaClient.class.getName()).log(Level.SEVERE, null, ex);
        }
}

public static void main(String[] args) throws IOException {
    GlobalQdaClient client = new GlobalQdaClient();
    client.start();
    while(!client.input.equals("end")){
        client.input = client.reader.readLine();
        try{
            client.out.writeUTF(client.input);
            if(client.in.available()>0){
            String data = client.in.readUTF();
            System.out.println("Recieved this: " + data);            
            }
        }
        catch(UnknownHostException ex){
            System.out.println(ex.getMessage());
        }
        catch(EOFException ex){
            System.out.println(ex.getMessage());
        }
        catch(IOException ex){
            System.out.println(ex.getMessage());
        }
    }
}    

@Override
public void run(){

    try {
        while(true){
            String data = in.readUTF();
            System.out.println("Recieved this: " + data);            
            }    
    } catch (IOException ex) {
            Logger.getLogger(Message.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM