简体   繁体   English

如何通过套接字将字符串从线程发送到服务器

[英]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 : 在服务器端,我正在尝试使用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 泰为您的建议

Taken from the docs from Scanner for hasNext(): 取自Scanner中针对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). 只要您的客户端仍处于连接状态,您的hasNext()调用就会被阻止,因为文件中没有已知的结尾(调用不会被阻止)。

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. 相反,您应该使用StringBuilder / StringBuffer。

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

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