简体   繁体   中英

Sending data through sockets in java

I am currently working on a one server many clients system. I am trying to get it so the server can send out one command, through a PrintWriter, that will go through to all of the clients connected on that socket. However in practice the command only goes through to one client. All of the clients are created on one socket, and all use the same Scanner. Is what I am trying to do possible?

Some code(incase it helps)

Creation of the socket:

serverSocketRefresh = new ServerSocket(PORTREFRESH);
refresh = serverSocketRefresh.accept();
Creation of the Print Writer and the Scanner:

networkOutputRefresh = new PrintWriter(refresh.getOutputStream(), true);
networkInput = new Scanner(refresh.getInputStream());

Ceation of the clients:

do
{
    // Wait for client...

    client = serverSocket.accept();
    System.out.println("\nNew client accepted.\n");
    handler = new ClientHandler(client,networkOutputRefresh, itemArray, bidderArray);
    handler.start();
} while (true);

The command im trying to transmit to all of the clients:

public static void updatePrice()
{   
    networkOutputRefresh.println("1");
}

Why not just use a BufferedReader and BufferedWriter, and make a new one each time you accept a client?

Edit: Or, if that '1' is the only thing you will ever send over that socket, just send it over the socket directly, as a byte. I believe the method is something like socket.write(new byte[] { 1 }, 0, 1) , and to read on the other end, socket.read(buffer, 0, 1) , where buffer is a byte array of length 1.

I am not sure if I correctly understand your code but it seems you are using a single reference of client. And your client reference will be holding the last client reference and hence the printwrite is writing only for that client. Ideally if you want to publish something to all the clients then you should have a collection of client references.Whenever you get an accept on the server socket, add the new client reference to your collection. And whenever you have to publish to all the clients just iterate over your client collection and publish using their associated printwriters.

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