Java EchoTCPServer - Send to all clients

2019-02-20 07:59发布

问题:

Here's my code:

SERVER:

package server;

public class Main {
    public static void main(String args[]) {
        new EchoServer(9000);
    }
}

+

package server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class EchoServer {
    private ServerSocket server;

    public EchoServer(int port) {
        try {
            server = new ServerSocket(port);

            while (true) {
                Socket socket = server.accept();

                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

                out.println(in.readLine() + " | MOD");

                socket.close();
            }
        } catch(Exception err) {
            err.printStackTrace();
        }
    }
}

CLIENT:

package client;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Main {
    public static void main(String args[]) {
        try {
            while (true) {
                Socket socket = new Socket("localhost", 9000);

                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

                BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

                out.println(input.readLine());

                System.out.println(in.readLine());

                socket.close();
            }
        } catch (Exception err) {
            System.out.println(err);
        }
    }
}

It works all as it should, except that I want when the server sends the "message" + " | MOD" to the client, I want the server to send that to all clients, how can I do that?

I am new to Java, but not to coding so please help me if I've done some wrong stuff that can be done easier or better.

Please help.

Thanks alot.

回答1:

What you can do is save the client sockets in an array, and then use a for loop to send to each socket.

First, declare your clientSocket array; note that 5 is just an arbitrary size used for testing. Also, declare a counter int.

public Socket clientSocket[] = new Socket[5];
public int intLastSocket = 0;

// this should be placed where you're waiting to accept connections
while (true) {
    printTCP("Ready to accept welcome socket");

    clientSocket[intLastSocket] = welcomeSocket.accept();

    intLastSocket++;
}

// on the server, call this to send. s is a reference to the server object
public void sendToAllTCP(TCPServer s, String message) {
    for (Socket z : s.clientSocket) {
        if (z != null) {
            PrintStream outToClient = null;
            try {
                outToClient = new PrintStream(z.getOutputStream());
                outToClient.println(message);
            } catch (IOException e) {
                TCPServer.printTCP("Caught an IO exception trying "
                        + "to send to TCP connections");
                e.printStackTrace();
            }
        }
    }
}

IN YOUR CODE:

package com.murplyx.server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class EchoServer {
    private ServerSocket server;
    // use the clientSocket Array to save each new connection
    public Socket clientSocket[] = new Socket[5];

    public EchoServer(int port) {
        try {
            server = new ServerSocket(port);

            // this should be placed where you're waiting to accept connections
            while (true) {
                System.out.println("Ready to accept welcome socket");

                clientSocket[intLastSocket] = server.accept();

                intLastSocket++;

                //send your message here, note that putting
                //it here will send it each time u add a new connection
                sendToAllTCP(/*the message you want to send */);
            }
        } catch(Exception err) {
            err.printStackTrace();
        }
    }

    public void sendToAllTCP(String message) {
        // this is an enchanced for loop, i don't know if it's in other languages
        // but in java it's supposed to let you loop through 
        //each object in any iterable list
        // such as array, arraylist, linkedlist, etc
        for (Socket z : clientSocket) {
            if (z != null) {
                //basically this chunk of code declares output and input streams 
                //for each socket in your array of saved sockets
                PrintStream outToClient = null;
                try {
                    outToClient = new PrintStream(z.getOutputStream());
                    outToClient.println(message);
                } catch (IOException e) {
                    System.out.println("Caught an IO exception trying "
                            + "to send to TCP connections");
                    e.printStackTrace();
                }
            }
        }
    }
}

Depending on when you want to send your message, you can use the console and sys.in to send it. For example, if you read a line from sys.in and it .equals("sendMsg"), then you can call sendToAllTCP(yourmessage)



回答2:

You should take a look at multiThreaded chat Server. Each client wich connects gets it's own thread.

Here is the perfect answer to your question:

multithread client-server chat, using sockets

Good luck mate!



标签: java tcp