Java:我没有收到其他客户的消息? [英] Java: I don't get the messages from other clients?

查看:134
本文介绍了Java:我没有收到其他客户的消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道我的代码有什么问题?

当我用client1写东西时,我只是在服务器和客户端1上看到它而不是在client2上看到它。

does anyone know whats wrong with my code?
When I write something with client1 i just see it on the server and on the client1 but not on client2.

run.java中的run():

run() in Client.java:

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

        }

如果您需要服务器代码或其他任何问题。

提前致谢!

If you need the Server code or anything else just ask.
Thanks in advance!!

此外服务器:

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或更高版本上使用。

This is an example - it is not complete but should give you an idea how you could multicast output to a number of listening clients. There are better ways to do this, but I wrote it similar to how you appeared to be doing the sockets. It also lacks error checking in many places and I have left that as an exercise for the reader. This code was also written so that it can be used on Java 1.6 or higher.

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

The code uses a list of connected Clients maintained in the Server object. When input is received from one client, the output is multicast to each client in the Client list. Writing is done via a write method in the Client class.

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:我没有收到其他客户的消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆