Java:我没有收到其他客户端的消息?

标签 java sockets stream client message

有人知道我的代码有什么问题吗?
当我用 client1 写一些东西时,我只在服务器和 client1 上看到它,但在 client2 上看不到它。

Client.java 中的 run():

public void run() {
        Scanner input = new Scanner(System.in);

        try {

            Socket client = new Socket(host, port);

            System.out.println("client started");

            OutputStream out = client.getOutputStream();
            PrintWriter writer = new PrintWriter(out);

            InputStream in = client.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                String i = input.nextLine();
                writer.write(clientname + ": " + i + newline);
                writer.flush();

                String s = null;

                while((s = reader.readLine()) != null) {

                    System.out.println(s);

                }

            writer.close();
            reader.close();
            client.close();

        }

如果您需要服务器代码或其他任何内容,请询问。
提前致谢!!

另外服务器:

public class Server {

    public static void main(String[] args) {
        int port = 40480;
        int max = 10;

        ExecutorService executor = Executors.newFixedThreadPool(max);

        try {
            ServerSocket server = new ServerSocket(port);
            System.out.print("server started" + "\n");

            while(true) {

                try {
                    Socket client = server.accept();

                    executor.execute(new Handler(client));

                }

                catch (IOException e) {
                    e.printStackTrace();

                }

            }

        } catch(Exception e) {
            e.printStackTrace();

        }

    }

}

和处理程序:

public class Handler implements Runnable{

    private Socket client;

    public Handler(Socket client) {
        this.client = client;

    }

    @Override
    public void run() {

        try {

            OutputStream out = client.getOutputStream();
            PrintWriter writer = new PrintWriter(out);

            InputStream in = client.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            String s = null;

            while((s = reader.readLine()) != null) {

                writer.write(s + "\n");
                writer.flush();

                System.out.println(s);

            }

            writer.close();
            reader.close();
            client.close();

        }

        catch(Exception e) {


        }

    }

}

最佳答案

这是一个示例 - 它并不完整,但应该让您了解如何将输出多播到多个监听客户端。有更好的方法可以做到这一点,但我写的方式与您似乎使用套接字的方式类似。它还在许多地方缺乏错误检查,我将其作为练习留给读者。该代码也是为了可以在 Java 1.6 或更高版本上使用而编写的。

该代码使用服务器对象中维护的已连接客户端列表。当从一个客户端接收到输入时,输出将多播到客户端列表中的每个客户端。写入是通过 Client 类中的 write 方法完成的。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MulticastEchoServer {
    List<Client> clientList = new LinkedList<Client>();
    ExecutorService executor;

    int port = 40480;
    int max = 10;

    public MulticastEchoServer() {
        this.executor = Executors.newFixedThreadPool(max);
    }

    public void writeToAllClients(String string) throws IOException {
        // Multiple threads access this so it must be in synchronized block
        synchronized (this.clientList) {
            Iterator<Client> iter = this.clientList.iterator();
            while (iter.hasNext())
                iter.next().write(string);
        }
    }

    public void addClient(Client client) {
        // Multiple threads access this so it must be in synchronized block
        synchronized (this.clientList) {
            clientList.add(client);
        }
    }

    public void removeClient(Client client) {
        // Multiple threads access this so it must be in synchronized block
        synchronized (this.clientList) {
            clientList.remove(client);
        }
    }

    public void listen() {
        try {
            ServerSocket server = new ServerSocket(port);
            System.out.println("server started and listening for connections");

            while (true) {
                try {
                    Socket socket = server.accept();
                    System.out.print("connection accepted" + "\n");

                    Client newClient = new Client(this, socket);

                    this.addClient(newClient);
                    this.executor.execute(newClient);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new MulticastEchoServer().listen();
    }

    private class Client implements Runnable {

        Socket socket;
        PrintWriter writer;
        BufferedReader reader;
        MulticastEchoServer server;

        public Client(MulticastEchoServer server, Socket socket) throws IOException {
            this.server = server;
            this.socket = socket;
            this.writer = new PrintWriter(this.socket.getOutputStream());
            this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        }

        synchronized public void write(String string) throws IOException {
            writer.write(string);
            writer.flush();
        }

        public void close() {
            this.writer.close();
            try {
                this.reader.close();
            } catch (IOException e) {
            }
            try {
                this.socket.close();
            } catch (IOException e) {
            }
        }

        @Override
        public void run() {
            System.out.println("Client Waiting");

            String inString = null;
            try {
                while ((inString = this.reader.readLine()) != null) {
                    this.server.writeToAllClients(inString + "\n");
                    System.out.println(inString);
                }
            } catch (IOException e1) {
            }

            server.removeClient(this);
            this.close();
            System.out.println("Client Closed");
        }
    }

}

关于Java:我没有收到其他客户端的消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25769206/

相关文章:

java - java中可以使用list来实现复合模式吗?

Java 1.4 : Cast primitive type to Object (Coupling vs Performance? )

java - android google guice框架时生成No class def found错误

c++ - Qt的QTcpSocket ReadyRead信号的实现

sockets - 为什么在执行 read() 时 ETH_P_IP 和 ETH_P_ALL 之间存在差异

c++ - 加载格式化的二进制文件并将信息分配给结构 c++

c# - XDocument.Load (XmlReader) 的性能很糟糕;来自 Web 服务的 2 MB XML 需要 4 秒才能从流中解析

swift - 在 Swift 中覆盖文件中的前 N ​​个字节

java - 覆盖 "when thread is released"行为的方法名称或机制是什么

c - 使用 C 在服务器端读取从客户端发送的文本文件