简体   繁体   English

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

[英]Server doesn't work with more than one connection

I've got a working simple client-server app. 我有一个简单的客户端 - 服务器应用程序。 The problem is it works fine just with one started client, but not with two or more. 问题是它只使用一个已启动的客户端,但没有两个或更多。 It establish connection, but when you try to enter text in first or second, the server breakes. 它建立连接,但是当您尝试在第一个或第二个文本中输入文本时,服务器会中断。 I think that problem may be at the function broadcast() in Server.java . 我认为问题可能出在Server.java中的函数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: 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();
            }
        }
    }

}

When opens two Client.java and connect it to the server.java everything is ok. 当打开两个Client.java并将其连接到server.java时,一切正常。 But when i try to send some message from this two opened clients server returns these errors: 但是,当我尝试从这两个打开的客户端服务器发送一些消息时,返回以下错误:

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)

What's happening is that your code scans the first line from the client ("sds", which is printed to stdout), and then it loops back and immediately tries to scan the next line from the client. 发生的事情是你的代码扫描客户端的第一行(“sds”,打印到stdout),然后它循环回来并立即尝试从客户端扫描下一行。 Since the client hasn't sent anything more yet, the input stream scanner throws an exception. 由于客户端尚未发送更多内容,因此输入流扫描程序会抛出异常。

The NewClient class is an inner class. NewClient类是一个内部类。 All instances of this class are created with the same instance of the outer class. 使用外部类的相同实例创建此类的所有实例。 Changing the code will sove the problem: 更改代码将解决问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM