服务器不能与多个连接一起使用

时间:2015-08-31 00:08:04

标签: java multithreading client-server

我有一个简单的客户端 - 服务器应用程序。问题是它只使用一个已启动的客户端,但没有两个或更多。它建立连接,但是当您尝试在第一个或第二个文本中输入文本时,服务器会中断。我认为问题可能出在broadcast()中的Server.java函数。

Server.java

public class Server {
    final int PORT = 5000;
    private ArrayList<NewClient> al = new ArrayList<NewClient>();
    private Scanner in;
    private PrintWriter out;
    private SimpleDateFormat sdf;
    private int uniqueID = 0;

    private void go(){

        try{
            ServerSocket serverSocket = new ServerSocket(PORT);
            System.out.println("Waiting for clients...");

            while(true) {
                Socket s = serverSocket.accept();
                NewClient chat = new NewClient(s);
                System.out.println("Client number " + chat.getId() + " connected from: " + s.getLocalAddress().getHostName());
                al.add(chat);
                Thread t = new Thread(chat);
                t.start();

            }
        }catch (Exception e) {
            System.out.println("Problem with establishing network connection: ");
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        Server server = new Server();
        server.go();
    }

    class NewClient implements Runnable{
        private Socket socket;
        private int id;

        public NewClient(Socket s) {
            this.socket = s;
            this.id = ++uniqueID;
        }
        public int getId() {
            return this.id;
        }

        @Override
        public void run() {
            try{
                in = new Scanner(socket.getInputStream());
                out = new PrintWriter(socket.getOutputStream());
                sdf = new SimpleDateFormat("HH:mm:ss");

                while(true) {
                    String input = in.nextLine();
                    System.out.println("Client said: " + input);
                    broadcast(input);
                }
            }catch (Exception e) {
                e.printStackTrace();
            }

        }
        private void writeMsg(String input) {
            String msg = input + " on " + sdf.format(new Date());
            out.println("You said: " + msg);
            out.flush();
        }

        private void broadcast(String input) {
            for (int i = 0; i < al.size(); i++) {
                NewClient t = al.get(i);
                t.writeMsg(input);
            }

        }
    }

}

Client.java:

public class Client {
    final int PORT = 5000;
    final String HOST = "127.0.0.1";
    private Scanner stdIn;
    private Scanner in;
    private PrintWriter out;


    private void go() {
        setUpNetwork();
    }

    private void setUpNetwork(){
        try{

            Socket s = new Socket(HOST, PORT);
            System.out.println("You are connected to " + HOST);
            NewClient client = new NewClient(s);
            Thread t = new Thread(client);
            t.start();
        } catch (Exception e) {
            System.out.println("Problem with connection to server: " + e);
        }
    }
    public static void main(String[] args) {
        Client client = new Client();
        client.go();
    }

    class NewClient implements Runnable {

        private Socket socket;
        public NewClient(Socket s) {
            this.socket = s;
        }

        @Override
        public void run() {
            try {
                stdIn = new Scanner(System.in);
                in = new Scanner(socket.getInputStream());
                out = new PrintWriter(socket.getOutputStream());

                while(true) {
                    System.out.print("> ");
                    String input = stdIn.nextLine();
                    out.println(input);
                    out.flush();

                    if(in.hasNext()) {
                        System.out.println(in.nextLine());
                    }
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

当打开两个Client.java并将其连接到server.java时,一切正常。但是当我尝试从这两个打开的客户端服务器发送一些消息时,会返回以下错误:

java.lang.IndexOutOfBoundsException: end
     at java.util.regex.Matcher.region(Matcher.java:1038)
     at java.util.Scanner.findPatternInBuffer(Scanner.java:1010)
Client said: sds
    at java.util.Scanner.findWithinHorizon(Scanner.java:1679)
    at java.util.Scanner.nextLine(Scanner.java:1538)
    at Server$NewClient.run(Server.java:66)
    at java.lang.Thread.run(Thread.java:745)

2 个答案:

答案 0 :(得分:0)

发生的事情是您的代码扫描客户端的第一行(&#34; sds&#34;,打印到stdout),然后它循环返回并立即尝试扫描下一行来自客户。由于客户端尚未发送任何内容,因此输入流扫描程序会抛出异常。

答案 1 :(得分:0)

NewClient类是一个内部类。使用外部类的相同实例创建此类的所有实例。更改代码将解决问题:

public NewClient(Socket s) {
            this.socket = s;
            this.id = ++uniqueID;
            try{
                in = new Scanner(socket.getInputStream());
                out = new PrintWriter(socket.getOutputStream());
                sdf = new SimpleDateFormat("HH:mm:ss");
            }catch(Exception e) {
                System.out.println("Exception while creating input/output streams: " + e);
            }
        }