开发者

When client sends a message to server, the message gets truncated

I'm new to multithreading. Im trying to do sending of messages between a client and a server. When I send a message to the server, my output in the server is supposed to be "Aji Computer: Thanks! :D", but instead I get a truncated data "Aji Computer: Thank".

Server code

    public QuoteServerThread(String name) throws IOException {
super(name);
socket = new DatagramSocket(4445);

 byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);

in.close();

socket.receive(packet);

String dString = "Wassup " + packet.getAddress().getHostName() + "!";
//if (in == null) dString = new Date().toString();
//else dString = getNextQuote();
buf = dString.getBytes();
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);

//THIS IS WHERE IM SUPPOSE TO PRINT "Aji Computer: Thanks! :D". But it prints out wrongly
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println(received);   
socket.close();

Client code

   DatagramSocket socket = new DatagramSocket();
    byte[] buf = new byte[256];
    InetAddress address = InetAddress.getByName("Aji Computer");
    DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
    socket.send(packet);
    packet = new DatagramPacket(buf, buf.length);
    socket.receive(packet);
    String received = new String(packet.getData(), 0, packet.getLength());
    System.out.println("Server: " + received);

    //THIS IS WHERE I SENT MY "Aji Computer: Thanks! :D" PACKET TO SERVER.
    buf = new byte[256];
    String str = "Aji Computer: Thanks! :D";
    buf = str.getBytes();
    packet = new DatagramPacket(buf, buf.length, address, 4445);
    socket.send(packet);
    socket.close();
开发者_开发百科

}

Just to let you know, this code is from Oracle. I modified a bit so that I would know how it works.


You reassign the size of your byte array from 256 bytes to: buf = dString.getBytes(); And further down in the program you created a new packet to receive on using packet = new DatagramPacket(buf, buf.length); This uses the length of dString.getBytes() instead of byte[256] I am assuming that dString.getBytes() has less space than "Aji Computer: Thanks!"

Try reassigning your byte array to its original value:

buf = new byte[256];

EDIT: removed 'byte' from above

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜