Posted 02 December 2012 - 05:07 AM
Sockets api in style Socket.IO
Easy Networking in Computercraft
Api
Spoiler
– Eventsconnect -server/client event when client connected (for server event, pass one argument Socket type )
– Server Socket Type
sockets.SOCKET_SERVER
– Client Socket Type
sockets.SOCKET_CLIENT
sockets.create( string socket_type, boolean debug) returns Socket
– Server/Client
Socket.on( string eventname, function( [event_arguments] ) ) returns Socket
– Server/Client
Socket.emit( string eventname [, table arguments] ) returns Socket
– Server
Socket.listen( void )
– Client
Socket.connect( [server computer id] )
Example
-- client side
local client = sockets.create(sockets.SOCKET_CLIENT)
client.on("connect", function()
client.on("ping", function(message)
print("Server ping")
client.emit("pong", message)
end)
end).connect()
-- Server side
local server = sockets.create(sockets.SOCKET_SERVER)
server.on("connect", function(socket)
socket.on("pong", function(message)
print("Client "..socket.id.." pong")
end)
socket.emit("ping")
end).listen()
Samples
Spoiler
ChatSpoiler
ClientSpoiler
local client = sockets.create(sockets.SOCKET_CLIENT) -- create client socket
local __NAME = nil -- define local name
function listen() -- listening thread
client.on("connect", function() -- bind to default "on connect" event (when connected to the server)
client.emit("setname", {__NAME}) -- send our name to the server
end).on("message", function(name, message) -- bind to "message" event
if name ~= nil and message ~= nil then -- if server pass all arguments
print(name..": "..message) -- print message on the screen
end
end).connect(8) -- connect to server with computer id 8
end
function sender() -- send thread
while true do -- always
local message = read() -- read local message
client.emit("message", {message}) -- call "message" event on the server
end
end
term.clear()
term.setCursorPos(1,1)
term.write("Enter your name: ")
__NAME = read()
parallel.waitForAll(listen, sender) -- start server threads
Server
Spoiler
local server = sockets.create(sockets.SOCKET_SERVER) -- create server socket
server.on("connect", function(socket) -- bind to "on connect" events (first argument is our connected client [color=#ff0000][b]Socket[/b][/color] type)
socket["name"] = "anonymouse" -- default name
socket.on("setname", function(name) -- when client trying to change name
if name ~= nil then -- if name is passed
socket["name"] = name -- set client name and bind it to client [b][color=#ff0000]Socket[/color][/b]
end
end)
socket.on("message", function(message) -- bind to "message" event
if message ~= nil then -- if message passed
print("[Chat]["..socket.id.."] "..socket.name..": "..message) -- write message on the server screen
server.emit("message", {socket.name, message}) -- broadcast message to all connected clients
end
end)
end).listen() -- start listening
Installation
Spoiler
Put sockets into .minecraft/mods/ComputerCraft/lua/rom/apisDownload
[attachment=725:sockets.zip]
pastebin