I'm trying to make node.js server and LÖVE2D client to communicate via sockets. (Just a simple "hello world" test.) Both node.js and LÖVE2D are running on the same PC.
I managed to send a message from LÖVE2D to node.js, but I can't read server's answer.
My node.js server code looks like this:
var net = require('net');
var mySocket;
var server = net.createServer(function(socket) {
mySocket = socket;
mySocket.on("connect", onConnect);
mySocket.on("data", onData);
});
function onConnect() {
console.log("Connected to LOVE2D");
}
function onData(d) {
if(d == "exit\0") {
console.log("exit");
mySocket.end();
server.close();
}
else {
console.log("Message from LOVE2D: " + d);
mySocket.write("Message received!", 'utf8');
}
}
server.listen(50000, "localhost");
And client code in LÖVE2D looks like this:
local host, port = "localhost", 50000
local socket = require("socket")
local tcp = assert(socket.tcp())
tcp:connect(host, port)
tcp:send("hello there")
tcp:close()
function love.draw()
love.graphics.print("can't read server answer!", 400, 300)
end
Well, the previous code just sends a message. What syntax should I use to read an answer from node.js server? For example this just gives me an error:
local host, port = "localhost", 50000
local socket = require("socket")
local tcp = assert(socket.tcp())
tcp:connect(host, port)
local answer = tcp:send("hello there")
tcp:close()
function love.draw()
love.graphics.print(answer, 400, 300)
end
Here is some documentation about networking in LÖVE2D & LuaSocket, but the documentation did not help me with this:
http://love2d.org/wiki/Tutorial:Networking_with_UDP
http://w3.impa.br/~diego/software/luasocket/
(Sorry for "noob" question, I'm really new with HTTP protocols and stuff.)
You need to use receive call as well:
tcp:connect(host, port)
tcp:send("hello there\n")
local answer = tcp:receive()
tcp:close()
function love.draw()
love.graphics.print(answer, 400, 300)
end
Be careful with new lines in your messages; the default "pattern" for receive
is to read one line (terminated by CR?LF), so if the end of line characters are not present, the receive operation will block waiting for them. The alternative would be to read a certain number of characters, but since you don't know the length of the message, you'd need to come up with some sort of the header (for example, send two bytes first that encode the length of the message that follows).
It's also possible to use a combination: send one line first and include the number of bytes in the payload that will follow (if any). For example "200 OK 135" or "500 ERROR", and then use that length (135 in the OK message) to read: tcp:receive(135)
.
If you end up using TCP-based protocol, you'll probably need to make it non-blocking, otherwise any network delay will block your game; see this SO answer for some pointers.