Berk ECER
Berk ECER

Reputation: 1

How can I send strings from Threads to Server via Sockets

In my thread class there is a section for sending information to Server. And I'm trying to send it via sockets like this:

PrintStream p = new PrintStream(sock.getOutputStream());

p.println(thread_name + "found : " + item);

And at the Server side I'm trying to reach the information with using InputStream:

    ServerSocket s1 = new ServerSocket(portNumber);
    System.out.println("Listening");*/

    ArrayList<Socket> sockets_list = new ArrayList<Socket>();
    ArrayList<Scanner> scanners_list = new ArrayList<Scanner>();
    for (int i = 0; i < Thread_Count; i++) {
        Socket news = s1.accept();
        sockets_list.add(news);
        Scanner newSc = new Scanner(sockets_list.get(i).getInputStream());
        scanners_list.add(newSc);
        System.out.println("socket added to server");

    }

    ArrayList<String> results = new ArrayList<String>();
    for (Scanner scanner : scan_list) {
        String res2 = "";
        while (scanner.hasNext()) {
            String res = scanner.next();
            res2 += res + " ";
        }
        if (!res2.equals("")) {
            results.add(res2);

        }

    }

    for (String string : results) {
        System.out.println(string);
    }

When I execute this code, it just outputs nothing or just one thread's information. How can I fix it ?

Ty for your advices

Upvotes: 0

Views: 60

Answers (1)

Lasse Meyer
Lasse Meyer

Reputation: 1479

Taken from the docs from Scanner for hasNext():

This method may block while waiting for input to scan.

As long as your clients are still connected, your hasNext() call will block, as there is no known end like in a file (where the call wouldn't block).

Note: This line is useless:

String res2 = "";

String is an imutable, so if you reassign something to it, it will create an entirely new object. Instead, you should use a StringBuilder/StringBuffer.

Upvotes: 1

Related Questions