简体   繁体   English

Java socket客户端不停止读取数据

[英]Java socket client doesn't stop reading the data

Hello i'm trying to execute a socket client in Java, but the client still reading the data and don't proceed with the program execution.您好,我正在尝试在 Java 中执行套接字客户端,但客户端仍在读取数据并且不继续执行程序。 Any ideas?有任何想法吗?

Here's the code:这是代码:

import java.io.*;
import java.net.Socket;

public class SocketTeste {

    public static void main(String[] args) {
        try {
            Socket client = new Socket("127.0.0.1", 1987);
            System.out.println("Got connection");
            DataInputStream handshake = new DataInputStream(client.getInputStream());
            String handshakePure = handshake.readUTF();
            System.out.println("Got the handshake");
            System.out.println(handshakePure);
            DataOutputStream saida = new DataOutputStream(client.getOutputStream());
            saida.writeUTF("Got it!");
            saida.flush();
            saida.close();
            String returnedData = handshake.readUTF();
            System.out.println(returnedData);
            handshake.close();
            client.close();
        } catch (Exception e) {
            System.out.println("ERROR: " + e);
        }
    }
}

I don't think if that matter, but the socket server is a PHP socket server.我认为这无关紧要,但套接字服务器是 PHP 套接字服务器。

DataInputStream.readUTF expects a uniquely weird message format. DataInputStream.readUTF需要一种独特的奇怪消息格式。 The first two bytes it reads are interpreted as the length of the string to read, in a big endian binary format.它读取的前两个字节被解释为要读取的字符串的长度,采用大端二进制格式。 This is then followed by a weird non-standard text encoding similar to but incompatible with UTF-8.然后是一个奇怪的非标准文本编码,类似于但不兼容 UTF-8。 Most likely you should not be using DataInputStream.readUTF to read data in a program, unless you used its counterpart DataOutputStream.writeUTF to write it in the first place.很可能您应该使用DataInputStream.readUTF来读取程序中的数据,除非您首先使用其对应的DataOutputStream.writeUTF来写入它。

Based on your comments it sounds like your communication protocol is based on lines of text.根据您的评论,听起来您的通信协议是基于文本行的。 To read lines of text, you can use for example the BufferedReader class.要读取文本行,您可以使用例如BufferedReader class。

BufferedReader handshake = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8));
String handshakePure = handshake.readLine();

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

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