Message sent in UDP datagram is not sanitized?

落花浮王杯 提交于 2019-12-04 06:23:53

问题


My code is as follows. Everything works the way I want it to, but when my messages are received they have many boxes on the end somewhat like this like this "Message: hello▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀" How can I make it so what is received and printed is only "Message: hello"? I greatly appreciate any help.

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

public class UDPChat {

    public static void main(String args[]) throws Exception {

        new UDPChat();
    }


    public UDPChat() {
        try {
            runChat();
        } catch (Exception e) {
        }}

    public void runChat() throws InterruptedException {
        Sender sender = new Sender();
        Receiver receiver = new Receiver();
        sender.start();
        receiver.start();
        sender.join();
        receiver.join();
    }

    class Receiver extends Thread {
        public void run() {
            try {
                DatagramSocket serverSocket = new DatagramSocket(9876);
                byte[] receiveData = new byte[1024];
                while (true) {
                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                    serverSocket.receive(receivePacket);
                    String sentence = new String(receivePacket.getData());
                    System.out.println("Message: " + sentence);
                }
            } catch (IOException e) {
            }
        }
    }

    class Sender extends Thread {
        public void run() {
            try {
                DatagramSocket clientSocket = new DatagramSocket();
                InetAddress IPAddress = InetAddress.getByName("localhost");
                byte[] sendData = new byte[1024];
                while (true) {
                BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
                String message = inFromUser.readLine();
                sendData = message.getBytes();

                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
                clientSocket.send(sendPacket);
                }
            } catch (IOException e) {
            }
        }
    }

}

回答1:


String sentence = new String(receivePacket.getData());

Usual problem. Ignoring the datagram length. Fix as follows:

String sentence = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength());


来源:https://stackoverflow.com/questions/37062459/message-sent-in-udp-datagram-is-not-sanitized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!