简体   繁体   English

无法在套接字列表的循环中获取套接字的DataOutputStream

[英]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. 我正在尝试使用Java创建客户端/服务器程序,其中客户端将简单的字符串发送到服务器,并且每个连接到服务器的客户端都将获得此字符串。 So I created 2 server classes for server which create new thread for each client and listen to them. 因此,我为服务器创建了2个服务器类,它们为每个客户端创建新线程并监听它们。 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. 我为此使用foreach循环。 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). 因此,只有此客户端会接收String(它自己发送)。 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 运行Client1
  • Run Client2 运行Client2
  • Send Message From Client1 ( Note That Client2 is now blocked because of input) 从Client1发送消息(请注意,由于输入,Client2现在被阻止)
  • Send Message From Client2 从Client2发送消息

Now you'll see the Message that sent previously from client1 on client2. 现在,您将在client2上看到先前从client1发送的消息。

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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