您可以从一个客户端发送到服务器,也可以从服务器接收到单独的客户端吗?

时间:2019-05-03 17:49:35

标签: java sockets object server client

我有2个客户课程。 [家长]和[孩子]我想从[家长]发送信息到服务器,并从服务器接收有关[孩子]的信息

我当时在想,也许是因为我需要使每个客户端都在一个新线程上,但是还没有在线程上做很多工作。

[服务器]

public class Server {

public static void main(String[] args) throws Exception {
    System.out.println("Server is ONLINE.");
    ExecutorService pool = Executors.newFixedThreadPool(500);
    try (ServerSocket listener = new ServerSocket(11111)) {
        while (true) {
            pool.execute(new Handler(listener.accept()));
        }
    }
}

private static class Handler implements Runnable, Serializable {

    private Socket socket;
    private ObjectInputStream in;
    private ObjectOutputStream out;

    public Handler(Socket socket) throws IOException {
        this.socket = socket;
    }

    public void run() {
        try {
            in = new ObjectInputStream(socket.getInputStream());
            out = new ObjectOutputStream(socket.getOutputStream());

            while (true){
                MouseCoordinates coord = (MouseCoordinates) 
in.readObject();
                System.out.println(coord.getX());
                System.out.println(coord.getY());
                out.writeObject(coord);
            }


        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }


    }
}
}

[父母]

public class Client {

private static ObjectOutputStream out;
private static ObjectInputStream in;
private static int x, y;

public static void main(String[] arg) throws IOException {
    System.out.println("Welcome Client.");

    Socket s = new Socket("127.0.0.1", 11111);

    System.out.println("You are connected.");

    out = new ObjectOutputStream(s.getOutputStream());
    System.out.println("Got the output stream.");

    x = 10;
    y = 11;

    out.writeObject(new MouseCoordinates(x, y));

    System.out.println("Information sent: " + new MouseCoordinates(x, y));
    System.out.println("Sending information to the server.");
}
}

[孩子]

public class OtherClient {
public static void main(String[] arg) throws IOException, 
ClassNotFoundException {

    Socket s = new Socket("127.0.0.1", 11111);


    //QUERY PASSING
    ObjectInputStream in = new ObjectInputStream(s.getInputStream());
    MouseCoordinates coords = (MouseCoordinates) in.readObject();

    System.out.println(coords);
}
}

预期:从[PARENT]发送到服务器,并在[CHILD]上从服务器接收

实际:从[PARENT]发送到服务器,但没有收到[CHILD]上的服务器

0 个答案:

没有答案