Advertisement
Guest User

network.lua

a guest
Jun 28th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.22 KB | None | 0 0
  1. local network = {}
  2.  
  3. local modem = require("component").modem
  4. local event = require("event")
  5.  
  6. ip = nil -- Here he has his own IP
  7.  
  8. function network.send(dip, port, message)
  9.    modem.open(port)
  10.    return modem.send(network.lookup(dip),port,ip,message)
  11. end
  12.  
  13. function network.receive(port, timeout)
  14.   modem.open(port)
  15.   while (true) do
  16.     local _,_,from,fport,_,fip,data = event.pull(timeout, "modem_message")
  17.     if(fport==port) then
  18.       local rip = network.lookup(fip)
  19.       if (rip==from) then
  20.         return rip,data
  21.       end
  22.     end
  23.   end
  24. end
  25.  
  26. function network.lookup(lip)
  27. --  print("lip: "..lip)
  28.   modem.open(1)
  29.   modem.broadcast(1, tostring("WHO IS " .. lip))
  30.  
  31.   while true do
  32.     local _,_,from,port,_,data = event.pull("modem_message")
  33.     --print("type: " ..type(data))
  34.     if type(data)=="string" then
  35.       --print(data)
  36.       local x = string.find(data," ")
  37.       local str1,str2 = string.sub(data,1,x-1),string.sub(data,x+1,#data)
  38.       if string.sub(str2,1,2) == "IS" then
  39.         local x = string.find(str2, " ")
  40.         local str3,str4 = string.sub(str2,1,x-1),string.sub(str2,x+1,#str2)
  41.         modem.close(1)
  42.         return(str4)
  43.       else
  44.         print("Corrupted data")
  45.       end
  46.  
  47.     end
  48.   end
  49.   modem.close(1)
  50.  
  51. end
  52.  
  53. return network
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement