简体   繁体   English

Java从套接字读取消息未发送完整消息

[英]Java reading message from socket is not sending full message

hello I am using this method to read a message: 你好,我正在使用这种方法来读取消息:

public String readMessage() {
    int read = -1;
    byte[] buffer = new byte[5*1024];
    byte[] redData;
    try {
        while ((read = this.session.getInputStream().read(buffer)) > -1) {
            redData = new byte[read];
            System.arraycopy(buffer, 0, redData, 0, read);
            return new String(redData,"UTF-8");

        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

And when I write something like "hello how are you today?" 当我写“你好,你今天好吗?”之类的东西时

Response (Exact format, including these new lines): 响应(精确格式,包括这些新行):

[/127.0.0.1:54930]:     
[/127.0.0.1:54930]: are

[/127.0.0.1:54930]: you

[/127.0.0.1:54930]: today?

Thats how I read chat messages, first I check which packet was requested, if the packet type was 0, then I get instance of packethandler, and pass the client object to the Chat handling packet which will read the message here, like this: 这就是我读取聊天消息的方式,首先我检查请求的数据包,如果数据包类型为0,然后获取packethandler的实例,然后将客户端对象传递给Chat处理数据包,该数据包将在此处读取消息,如下所示:

public void startClientService() throws IOException {
    while(true) {
        int packetType = this.in.read();
        packets.getPacket(packetType);
    }
}
public void getPacket(int packetType) {
    switch (packetType) {
    case 0:
        chat.processPacket(this.client);
        break;
    }
}

And the chat packet: 和聊天包:

@Override
public void processPacket(Session c) {
    String clientMessage = c.readMessage();
    System.out.println("[" + c.getStream().getRemoteSocketAddress() + "]: " + clientMessage.toString());
}

And there the print message happens. 并出现打印消息。

Why does it print parts of the messages, in new lines? 为什么它用新行打印部分消息? not even the full message. 甚至没有完整的消息。

This is my client: 这是我的客户:

public static void main(String[] args) throws UnknownHostException, IOException {
    Socket socket = new Socket("127.0.0.1", 43594);
    Scanner r = new Scanner(System.in);
    PrintWriter out = new PrintWriter(socket.getOutputStream());
    String input;
    while(true) {
        input = r.next();
        if (input != null) {
            sendMessage(input, out);
        }
    }

}

public static void sendMessage(String message, PrintWriter out) {
    out.write(0);
    out.flush();
    out.write(message + "\n");
    out.flush();
}

Thanks. 谢谢。

Session: 会议:

public class Session extends Thread implements Runnable {

    private Socket session;
    private Client client;
    private PrintWriter out;
    private BufferedReader in;  
    private PacketHandler packets;

    public Session(Socket session) {
        this.session = session;
        this.client = new Client(this);
        try {
            this.setStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.packets = new PacketHandler(this);
        System.out.println("[New session created]: " + session.getRemoteSocketAddress());
    }   

    public void run() {
        try {
            this.startClientService();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Socket getStream() {
        return this.session;
    }

    public void setStream() throws IOException {
        this.out = new PrintWriter(this.session.getOutputStream());
        this.in = new BufferedReader(new InputStreamReader(this.session.getInputStream()));
    }

    public Client getClient() {
        return this.client;
    }

    public String readMessage() {
        int read = -1;
        byte[] buffer = new byte[5*1024];
        byte[] redData;
        try {
            while ((read = this.session.getInputStream().read(buffer)) > -1) {
                redData = new byte[read];
                System.arraycopy(buffer, 0, redData, 0, read);
                return new String(redData,"UTF-8");

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void startClientService() throws IOException {
        while(true) {
            int packetType = this.in.read();
            packets.getPacket(packetType);
        }
    }

    public void destruct() throws IOException {
        this.session.close();
        System.out.println("Session killed");
    }

}

looks like you are returning as soon as you get some data from stream. 看起来只要您从流中获取了一些数据,您就将返回。

  while ((read = this.session.getInputStream().read(buffer)) > -1) {
            redData = new byte[read];
            System.arraycopy(buffer, 0, redData, 0, read);
            return new String(redData,"UTF-8");

        }

Read the data completely and make a string object out of it and return it 完全读取数据,并从中创建一个字符串对象并返回

    BufferedReader br = new BufferedReader(new InputStreamReader(this.session.getInputStream()));
String msg = br.readLine();
br.close();
    return msg;

try this way. 尝试这种方式。 This will give you entire data to a buffer and can return as line of string.No need of loop 这会将全部数据提供给缓冲区,并且可以作为字符串行返回。

The the amount of data returned from one call to read has no relationship to how the data divided when sent. 从一次调用读取返回的数据量与发送时数据如何划分无关。 One send can result in any number of reads, and multiple sends may be combined into one read. 一个发送可以导致任何数量的读取,并且多个发送可以组合为一个读取。

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

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