Frage

Okay, so I have a project where I'm working with a Client (written in Lua) and a Server (written in Java). I'm using LuaSocket for the client and DatagramSockets for the server. The problem is when I send one string from the client in Lua, and receive it on the server(and convert the bytes to a string), it doesn't recognize the value of the string as equal to what it should be(I'm using .equals() for evaluation). I've printed the result and compared it to the string(everything checked out); I've even compared the bytes (using .getBytes()), they even checked out. The most annoying part of this is that when I analyze the string with .startsWith() it evaluates true, but nothing else works. I've looked into the string encoding of both languages, but I'm relatively new to sockets and this is beyond me.

Edit:

Upon writing some example code to demonstrate the problem, I solved it. Here is the code:

Client:

local socket = require "socket"
local udp = socket.udp()
udp:settimeout(0)
udp:setpeername("localhost", 1234)
udp:send("foo")

Server:

public class Main 
{
        public static void main(String args[]) throws Exception
    {
        DatagramSocket server = new DatagramSocket(1234);

        byte[] incomingBytes = new byte[512];

        DatagramPacket incomingPacket = new DatagramPacket(incomingBytes, incomingBytes.length);

        server.receive(incomingPacket);

        String received = new String(incomingBytes);

        System.out.println(received);

        System.out.println(received.equals("foo"));

        for (byte b : received.getBytes())
        {
            System.out.print(b + "    ");
        }
        System.out.print("\n");

        for (byte b : "foo".getBytes())
        {
            System.out.print(b + "    ");
        }
        System.out.print("\n");
    }
}

The result:

foo
false
102    111    111    0    0    0   *I'm not going to include all but there are 506 more*   
102    111    111    

The string I had been examining the bytes from previously was split at several points, and that would explain why I didn't notice this.

War es hilfreich?

Lösung

Indeed as Etan pointed out, you're creating a string from the entire buffer--all 512 bytes--instead of a string of the correct length, so the string that is created has lots of zero bytes at the end.

A simple fix would be to use the String constructor that cuts off the buffer at the position and length you specify, along with the number of bytes received from the packet from DatagramPacket.getLength

Change the line assigning received to

String received = new String(incomingBytes, 0, incomingPacket.getLength());
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top