diff --git a/README.html b/README.html deleted file mode 100644 index bcd1469..0000000 --- a/README.html +++ /dev/null @@ -1,184 +0,0 @@ - - - - - README.html - - - - - - -

net (2.0.1)

Updated from 2.0.0 to 2.0.1
Added:

Discord

For real-time assistance with my libraries! A place where you can ask questions and get help with any of my libraries

https://discord.gg/U8UspuA

The net library was created to make servers and clients interact easily. This isn’t for webservers! (It could be, but you would need to code that part) The goal was to allow the creation for game servers!

This library depends on luasocket and you should use luajit! It will work on a standard lua interperter, but wont be as fast.

Goal

A simple and powerful way to make servers and clients

Todo

Note

You will see a bunch of files inside of the net folder. All that is stable is the init.lua and sft.lua file. Everything else is a work in progress. Plus I am planning on rewritting all of the modules to take advantage of the new threading features that are found in the new multi updates. PRogress on this will be made soon. I have just been away from my PC for a while.

Usage

server.lua

require("bin") -- this library needs a lot of work it has a bunch of old useless code, but also has many nice things as well that are really useful
-require("multi") -- you need this to handle multiple connections and such
-require("net") -- That requires the main library
-server=net:newTCPServer(12345) -- create a server that listens on port 12345
-server.OnDataRecieved(function(self,data,CID_OR_HANDLE,IP_OR_HANDLE,PORT_OR_IP,UPDATER_OR_NIL) -- a bit confusing, but dont worry you will hardly ever need more then the first 5 arguments, unless you are writing modules!
-  if data=="Hello!" then
-    print("Got response from client sending back data!")
-    self:send(IP_OR_HANDLE,"Hello Client!",PORT_OR_IP) -- doing it like this makes this code work for both udp and tcp
-  end
-end)
-multi:mainloop()
-

client.lua

require("bin") -- this library needs a lot of work it has a bunch of old useless code, but also has many nice things as well that are really useful
-require("multi") -- you need this to handle multiple connections and such
-require("net") -- That requires the main library
-client=net:newTCPClient("localhost",12345) -- connect to the server
-client.OnClientReady(function(self)
-  self:send("Hello!")
-end) -- For a tcp client the client is already ready, with udp a small handshake is done and the client is not instantly ready
-client.OnDataRecieved(function(self,data) -- thats it clients only have to worry about itself and the server
-  if data=="Hello Client!" then
-    print("Server Responded Back!")
-  end
-end)
-multi:mainloop()
-

There is support for broadcasting, multicasting will be added soon requires luasocker 3.0+.

Here is a broadcasting example:

broadcastingExampleServer.lua (included in example folders)

package.path="?/init.lua;"..package.path
--- Note: you need 2 computers to test this! Broadcast does not on local host!
--- I have tested this code and it works, but only on seperate PC's within the same LAN network
-require("bin")
-require("multi")
-require("net")
-server=net:newServer(12345)
-server.OnDataRecieved(function(self,data,CID_OR_HANDLE,IP_OR_HANDLE,PORT_OR_IP,UPDATER_OR_NIL)
-    if data=="Hello!" then -- copy from other example
-        print("Got response from client sending back data!")
-        self:send(IP_OR_HANDLE,"Hello Client!",PORT_OR_IP) -- doing it like this makes this code work for both udp and tcp
-    end
-end)
-server:broadcast("Lua_Server")
-multi:mainloop()
-

broadcastingExampleClient.lua (included in example folders)

package.path="?/init.lua;"..package.path
-require("bin")
-require("multi")
-require("net.aft")
-client=net:newCastedClient("Lua_Server") -- searches the lan for this server name
--- Both udp and tcp clients can be broadcasted
-client.OnClientReady(function(self)
-    self:send("Hello!")
-end) -- For a tcp client the client is already ready, with udp a small handshake is done and the client is not instantly ready
-client.OnDataRecieved(function(self,data) -- thats it clients only have to worry about itself and the server
-    if data=="Hello Client!" then
-        print("Server Responded Back!")
-    end
-end)
-multi:mainloop()
-

The net library also provides a powerful module creation interface. You have all of the modules in the net folder as examples, however I will show you how you could go about creating your own!

All functions include:

Both TCP/UPD Clients and Servers contain the same methods:
Server Object:

General Server Methods

TCP Server Only Methods

General Client Methods

UDP Client Only Methods

TCP Client Only Methods

When using the module creation support here is the shell that you can use:

require("net") -- what do you need? other modules or the core? always require the core so users can require your module without having to require the core themself
-local MODULENAME="EXAMPLE"
-net:registerModule(MODULENAME,{1,0,0})
-if not io.dirExists(string.upper(MODULENAME)) then -- do you need a directory to store stuff for your module?
-    io.mkDir(string.upper(MODULENAME))
-end
-net.OnServerCreated:connect(function(s)
-    s.OnDataRecieved(function(self,data,CID_OR_HANDLE,IP_OR_HANDLE,PORT_OR_IP)
-        local cmd,arg1,arg2=data:match("!"..MODULENAME.."! (%S+) (%S+) (%S+)") -- change to fit your needs
-        if cmd=="SEND" then
-            --
-        elseif cmd=="GET" then
-            --
-        end
-    end,MODULENAME)
-end)
-net.OnClientCreated:connect(function(c)
-    c.OnDataRecieved(function(self,data)
-        local cmd,arg1,arg2=data:match("!"..MODULENAME.."! (%S+) (%S+) (%S+)") -- change to fit your needs
-        if cmd=="SEND" then
-            --
-        elseif cmd=="GET" then
-            --
-        end
-    end,MODULENAME)
-end)
-

The bin and multi library can be found on my github page. They are all ‘100%’(If you ingore intergrations) pure lua so it should be easy to add to your project.
https://github.com/rayaman/multi
https://github.com/rayaman/bin

- - - - diff --git a/README.md b/README.md index c6ad1f9..c1f41fe 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,6 @@ -# net (2.0.1) -Updated from 2.0.0 to 2.0.1 -Added: -- Examples -- Support for latest multi version -- Updated readme +# net (5.0.0) Total Rewrite +I've returned to this project. Mainly to create a way to test my multi-tasking library. Notable features, create server/client connections that work async. Added wrapper for http and https request (multi, luasocket and luasec required) to work in coroutines without needing a lua-core modifacation. # Discord For real-time assistance with my libraries! A place where you can ask questions and get help with any of my libraries
@@ -39,7 +35,7 @@ require("bin") -- this library needs a lot of work it has a bunch of old useless require("multi") -- you need this to handle multiple connections and such require("net") -- That requires the main library server=net:newTCPServer(12345) -- create a server that listens on port 12345 -server.OnDataRecieved(function(self,data,CID_OR_HANDLE,IP_OR_HANDLE,PORT_OR_IP,UPDATER_OR_NIL) -- a bit confusing, but dont worry you will hardly ever need more then the first 5 arguments, unless you are writing modules! +server.OnDataRecieved(function(self, data, CID, IP, PORT) -- a bit confusing, but dont worry you will hardly ever need more then the first 5 arguments, unless you are writing modules! if data=="Hello!" then print("Got response from client sending back data!") self:send(IP_OR_HANDLE,"Hello Client!",PORT_OR_IP) -- doing it like this makes this code work for both udp and tcp diff --git a/client.lua b/client.lua new file mode 100644 index 0000000..43b2850 --- /dev/null +++ b/client.lua @@ -0,0 +1,45 @@ +package.path = "./?/init.lua;./?.lua;"..package.path +-- local net = require("net.tcp") +-- local client = net:newTCPClient("localhost",12345) + +-- client:send("Test!") + +-- client.OnDataRecieved(function(c,data) +-- print("Response: ",data) +-- --c:send("Testing again!") +-- end) + +local multi, thread = require("multi"):init() +local https = require("net.https") + +-- multi:newThread("test1",function() +-- local file = io.open("test1.jpg","wb") +-- data, code, headers, status = http.request("http://zjcdn.manga3fox.me/store/manga/33769/091.0/compressed/s20210705_163050_598.jpg") +-- print("Data:",data) +-- if headers then +-- for i,v in pairs(headers) do +-- print(i,v) +-- end +-- end +-- print(data,code,headers,status) +-- file:write(data) +-- file:flush() +-- file:close() +-- os.exit() +-- end).OnError(function(a,b,c) +-- print("Error: ",a,b,c) +-- --os.exit() +-- end) + +data, code, headers, status = https.request("https://example.com/") +print(data, code, headers, status) +if headers then + for i,v in pairs(headers) do + print(i,v) + end +end + +-- multi.OnExit(function() +-- print("Lua state being shutdown! :'(") +-- end) +-- multi:mainloop() \ No newline at end of file diff --git a/net/https.lua b/net/https.lua new file mode 100644 index 0000000..7d4740a --- /dev/null +++ b/net/https.lua @@ -0,0 +1,146 @@ +---------------------------------------------------------------------------- +-- LuaSec 1.0.1 +-- Copyright (C) 2009-2021 PUC-Rio +-- +-- Author: Pablo Musa +-- Author: Tomas Guisasola +--------------------------------------------------------------------------- + +local socket = require("socket") +local ssl = require("ssl") +local ltn12 = require("ltn12") +local http = require("net.http") +local url = require("socket.url") + +local try = socket.try + +-- +-- Module +-- +local _M = { + _VERSION = "1.0.1", + _COPYRIGHT = "LuaSec 1.0.1 - Copyright (C) 2009-2021 PUC-Rio", + PORT = 443, + TIMEOUT = 60 +} + +-- TLS configuration +local cfg = { + protocol = "any", + options = {"all", "no_sslv2", "no_sslv3", "no_tlsv1"}, + verify = "none", +} + +-------------------------------------------------------------------- +-- Auxiliar Functions +-------------------------------------------------------------------- + +-- Insert default HTTPS port. +local function default_https_port(u) + return url.build(url.parse(u, {port = _M.PORT})) +end + +-- Convert an URL to a table according to Luasocket needs. +local function urlstring_totable(url, body, result_table) + url = { + url = default_https_port(url), + method = body and "POST" or "GET", + sink = ltn12.sink.table(result_table) + } + if body then + url.source = ltn12.source.string(body) + url.headers = { + ["content-length"] = #body, + ["content-type"] = "application/x-www-form-urlencoded", + } + end + return url +end + +-- Forward calls to the real connection object. +local function reg(conn) + local mt = getmetatable(conn.sock).__index + for name, method in pairs(mt) do + if type(method) == "function" then + conn[name] = function (self, ...) + return method(self.sock, ...) + end + end + end +end + +-- Return a function which performs the SSL/TLS connection. +local function tcp(params) + params = params or {} + -- Default settings + for k, v in pairs(cfg) do + params[k] = params[k] or v + end + -- Force client mode + params.mode = "client" + -- 'create' function for LuaSocket + return function () + local conn = {} + conn.sock = try(socket.tcp()) + local st = getmetatable(conn.sock).__index.settimeout + function conn:settimeout(...) + return st(self.sock, _M.TIMEOUT) + end + -- Replace TCP's connection function + function conn:connect(host, port) + try(self.sock:connect(host, port)) + self.sock = try(ssl.wrap(self.sock, params)) + self.sock:sni(host) + self.sock:settimeout(_M.TIMEOUT) + try(self.sock:dohandshake()) + reg(self, getmetatable(self.sock)) + return 1 + end + return conn + end +end + +-------------------------------------------------------------------- +-- Main Function +-------------------------------------------------------------------- + +-- Make a HTTP request over secure connection. This function receives +-- the same parameters of LuaSocket's HTTP module (except 'proxy' and +-- 'redirect') plus LuaSec parameters. +-- +-- @param url mandatory (string or table) +-- @param body optional (string) +-- @return (string if url == string or 1), code, headers, status +-- +local function request(url, body) + local result_table = {} + local stringrequest = type(url) == "string" + if stringrequest then + url = urlstring_totable(url, body, result_table) + else + url.url = default_https_port(url.url) + end + if http.PROXY or url.proxy then + return nil, "proxy not supported" + elseif url.redirect then + return nil, "redirect not supported" + elseif url.create then + return nil, "create function not permitted" + end + -- New 'create' function to establish a secure connection + url.create = tcp(url) + local res, code, headers, status = http.request(url) + if res and stringrequest then + return table.concat(result_table), code, headers, status + end + return res, code, headers, status +end + +-------------------------------------------------------------------------------- +-- Export module +-- + +_M.request = request +_M.tcp = tcp + +return _M diff --git a/net/init.lua b/net/init.lua index 5937112..db52f85 100644 --- a/net/init.lua +++ b/net/init.lua @@ -44,9 +44,6 @@ math.random() math.random() local multi, thread = require("multi").init() local socket = require("socket") -local http = require("socket.http") -local https=require("ssl.https") -local mime = require("mime") --ssl=require("ssl") --https=require("ssl.https") local net = {} @@ -198,736 +195,4 @@ function net:newCastedClients(name) -- connects to the broadcasted server end end) end --- -- UDP Stuff --- function net:newUDPServer(port, servercode, nonluaServer) --- local c = {} --- c.udp = assert(socket.udp()) --- c.udp:settimeout(0) --- c.udp:setsockname("*", port) --- c.ips = {} --- c.Type = "udp" --- if port == 0 then --- _, c.port = c.udp:getsockname() --- end --- c.ids = {} --- c.servercode = servercode --- c.bannedIPs = {} --- c.bannedCIDs = {} --- c.autoNormalization = false --- function c:setUpdateRate(n) --- --print("Not needed in a udp server!") --- end --- function c:banCID(cid) --- table.insert(self.bannedCIDs, cid) --- end --- function c:banIP(ip) --- table.insert(self.bannedIPs, cid) --- end --- c.broad = socket.udp() --- c.hostip = net.getLocalIP() --- function c:broadcast(name) --- table.insert(net.BroadcastDriver, --- function(loop, dt) --- self.broad:setoption("broadcast", true) --- self.broad:sendto(name .. "|" .. self.Type .. "|" .. self.hostip .. ":" .. self.port, "255.255.255.255", 11111) --- self.broad:setoption("broadcast", false) --- end) --- end --- function c:send(ip, data, port, cid) --- if self.autoNormalization then --- data = net.normalize(data) --- end --- if self.servercode then --- cid = cid or self:CIDFrom(ip, port) --- if not self.ips[cid] then --- --print("Can't determine cid from client... sending the client a new one!") --- local cid = net.resolveID(self) --- --print("Sending unique cid to client: " .. cid) --- self.ips[cid] = {ip, port, 0, self.servercode == nil} --- --print(ip) --- self.udp:sendto("I!" .. cid, ip, port) --- if self.servercode then --- self.udp:sendto("S!", ip, port) --- end --- return --- end --- if net.inList(self.bannedIPs, ip) or net.inList(self.bannedCIDs, cid) then --- self.udp:sendto("BANNED CLIENT", ip, port or self.port) --- elseif self.ips[cid][4] then --- self.udp:sendto(data, ip, port or self.port) --- elseif self.ips[cid][4] == false then --- self.udp:sendto("Make sure your server code is correct!", ip, port) --- end --- else --- self.udp:sendto(data, ip, port or self.port) --- end --- end --- function c:pollClientModules(ip, port) --- self:send(ip, "L!", port) --- end --- function c:CIDFrom(ip, port) --- for i, v in pairs(self.ips) do --- if (ip == v[1] and v[2] == port) then --- return i --- end --- end --- end --- function c:sendAll(data) --- for i, v in pairs(self.ips) do --- self:send(v[1], data, v[2], i) --- end --- end --- function c:sendAllBut(data, cid) --- for i, v in pairs(self.ips) do --- if i ~= cid then --- self:send(v[1], data, v[2], i) --- end --- end --- end --- function c:clientRegistered(cid) --- return self.cids[cid] --- end --- function c:clientLoggedIn(cid) --- if not self.clientRegistered(cid) then --- return nil --- end --- return self.ips[cid][4] --- end --- function c:update() --- local data, ip, port = self.udp:receivefrom() --- if net.inList(self.bannedIPs, ip) or net.inList(self.bannedCIDs, cid) then --- --print("We will ignore data from a banned client!") --- return --- end --- if data then --- if self.autoNormalization then --- data = net.denormalize(data) --- end --- if data:sub(1, 4) == "pong" then --- --print("Recieved pong from: "..data:sub(5,-1)) --- self.ips[data:sub(5, -1)][3] = os.clock() --- elseif data:sub(1, 2) == "S!" then --- local cid = self:CIDFrom(ip, port) --- if data:sub(3, -1) == self.servercode then --- --print("Servercode Accepted: " .. self.servercode) --- if self.ips[cid] then --- self.ips[cid][4] = true --- else --- --print("Server can't keep up! CID: " .. cid .. " has been skipped! Sending new CID to the client!") --- local cid = net.resolveID(self) --- --print("Sending unique cid to client: " .. cid) --- self.ips[cid] = {ip, port, 0, self.servercode == nil} --- --print(ip) --- self.udp:sendto("I!" .. cid, ip, port) --- if self.servercode then --- self.udp:sendto("S!", ip, port) --- end --- end --- else --- self.udp:sendto("Make sure your server code is correct!", ip, port) --- end --- elseif data:sub(1, 2) == "C!" then --- local hook = (data:sub(11, -1)):match("!(.-)!") --- self.OnDataRecieved:getConnection(hook):Fire(self, data:sub(11, -1), data:sub(3, 10), ip, port) --- elseif data:sub(1, 2) == "E!" then --- self.ips[data:sub(3, 10)] = nil --- obj.ids[data:sub(3, 10)] = false --- self.OnClientClosed:Fire(self, "Client Closed Connection!", data:sub(3, 10), ip, port) --- elseif data == "I!" then --- local cid = net.resolveID(self) --- --print("Sending unique cid to client: " .. cid) --- self.ips[cid] = {ip, port, os.clock(), self.servercode == nil} --- --print(ip) --- self.udp:sendto("I!" .. cid, ip, port) --- if self.servercode then --- self.udp:sendto("S!", ip, port) --- end --- self.OnClientConnected:Fire(self, cid, ip, port) --- elseif data:sub(1, 2) == "L!" then --- cid, cList = data:sub(3, 10), data:sub(11, -1) --- local list = {} --- for m, v in cList:gmatch("(%S-):(%S-)|") do --- list[m] = v --- end --- self.OnClientsModulesList:Fire(list, cid, ip, port) --- end --- end --- for cid, dat in pairs(self.ips) do --- if not ((os.clock() - dat[3]) < 65) then --- self.ips[cid] = nil --- self.OnClientClosed:Fire(self, "Client lost Connection: ping timeout", cid, ip, port) --- end --- end --- end --- c.OnClientsModulesList = multi:newConnection() --- c.OnDataRecieved = multi:newConnection() --- c.OnClientClosed = multi:newConnection() --- c.OnClientConnected = multi:newConnection() --- c.connectiontest = multi:newAlarm(30):setName("net.pingOutTask") --- c.connectiontest.link = c --- c.connectiontest:OnRing( --- function(alarm) --- alarm.link:sendAll("ping") --- alarm:Reset() --- end --- ) --- table.insert(net.ConnectionDriver, c) --- net.OnServerCreated:Fire(c) --- return c --- end --- local pingManager = {} --- function net:newUDPClient(host, port, servercode, nonluaServer) --- local c = {} --- c.ip = assert(socket.dns.toip(host)) --- c.udp = assert(socket.udp()) --- c.udp:settimeout(0) --- c.udp:setpeername(c.ip, port) --- c.cid = "NIL" --- c.lastPing = 0 --- c.Type = "udp" --- c.servercode = servercode --- c.autoReconnect = true --- c.autoNormalization = false --- function c:pollPing(n) --- return not ((os.clock() - self.lastPing) < (n or 60)) --- end --- function c:send(data) --- if self.autoNormalization then --- data = net.normalize(data) --- end --- self.udp:send("C!" .. self.cid .. data) --- end --- function c:sendRaw(data) --- if self.autoNormalization then --- data = net.normalize(data) --- end --- self.udp:send(data) --- end --- function c:getCID() --- if self:IDAssigned() then --- return self.cid --- end --- end --- function c:close() --- self:send("E!") --- end --- function c:IDAssigned() --- return self.cid ~= "NIL" --- end --- function c:update() --- local data = self.udp:receive() --- if data then --- if self.autoNormalization then --- data = net.denormalize(data) --- end --- if data:sub(1, 2) == "I!" then --- self.cid = data:sub(3, -1) --- self.OnClientReady:Fire(self) --- elseif data == "S!" then --- self.udp:send("S!" .. (self.servercode or "")) --- elseif data == "L!" then --- local mods = "" --- local m = "" --- for i = 1, #net.loadedModules do --- m = net.loadedModules[i] --- mods = mods .. m .. ":" .. net.getModuleVersion(m) .. "|" --- end --- self.udp:send("L!" .. self.cid .. mods) --- elseif data == "ping" then --- self.lastPing = os.clock() --- self.OnPingRecieved:Fire(self) --- self.udp:send("pong" .. self.cid) --- else --- local hook = data:match("!(.-)!") --- self.OnDataRecieved:getConnection(hook):Fire(self, data) --- end --- end --- end --- function c:reconnect() --- if not nonluaServer then --- self.cid = "NIL" --- c.udp:send("I!") --- end --- self.pingEvent:Resume() --- self.OnConnectionRegained:Fire(self) --- end --- c.pingEvent = --- multi:newEvent( --- function(self) --- return self.link:pollPing() --- end --- ) --- c.pingEvent:OnEvent( --- function(self) --- if self.link.autoReconnect then --- self.link.OnServerNotAvailable:Fire("Connection to server lost: ping timeout! Attempting to reconnect...") --- self.link.OnClientDisconnected:Fire(self, "closed") --- self.link:reconnect() --- else --- self.link.OnServerNotAvailable:Fire("Connection to server lost: ping timeout!") --- self.link.OnClientDisconnected:Fire(self, "closed") --- end --- self:Pause() --- end --- ):setName("net.pingInTask") --- c.pingEvent.link = c --- c.OnPingRecieved = multi:newConnection() --- c.OnDataRecieved = multi:newConnection() --- c.OnServerNotAvailable = multi:newConnection() --- c.OnClientReady = multi:newConnection() --- c.OnClientDisconnected = multi:newConnection() --- c.OnConnectionRegained = multi:newConnection() --- c.notConnected = --- multi:newFunction( --- function(self) --- multi:newAlarm(3):OnRing( --- function(alarm) --- if self.link:IDAssigned() == false then --- self.link.OnServerNotAvailable:Fire("Can't connect to the server: no response from server") --- end --- alarm:Destroy() --- end --- ):setName("net.clientTimeout") --- end --- ) --- c.notConnected.link = c --- if not nonluaServer then --- c.udp:send("I!") --- end --- table.insert(net.ConnectionDriver, c) --- multi.nextStep( --- function() --- c.notConnected() --- end --- ) --- net.OnClientCreated:Fire(c) --- return c --- end ---TCP Stuff --- function net:newTCPClientObject(fd) --- local c = {} --- local client --- c.Type = "tcp-ClientObj" --- c.rMode = "*l" --- c.sMode = "*l" --- function c:packMsg(data) --- local temp = bin.new() --- temp:addBlock(#data, self.numspace, "n") --- temp:addBlock(data) --- return temp:getData() --- end --- function c:enableBinaryMode() --- self.rMode = "b" --- self.sMode = "b" --- end --- if fd then --- client = socket.tcp() --- client:setfd(fd) --- _, port = client:getsockname() --- c.handle = client --- else --- error("You need to enter a fd in order to be able to create a tcp client object like this!") --- end --- function c:setUpdateRate(n) --- self.updaterRate = n --- end --- function c:setReceiveMode(mode) --- self.rMode = mode --- end --- function c:setSendMode(mode) --- self.rMode = mode --- end --- function c:send(data) --- if self.autoNormalization then --- data = net.normalize(data) --- end --- if self.sMode == "*l" then --- self.handle:send(data .. "\n") --- elseif self.sMode == "b" then --- self.handle:send(self:packMsg(data)) --- else --- self.handle:send(data) --- end --- end --- multi:newThread("ServerClientHandler",function() --- while true do --- thread.skip(1) --- local data, err, dat, len --- if self.rMode == "b" then --- thread.hold(function() --- return client:receive(self.numspace) --- end) --- len = bin.new(dat):getBlock("n", self.numspace) --- data, err = client:receive(len) --- else --- data, err = client:receive(self.rMode) --- end --- if err == "closed" then --- for i = 1, #self.ips do --- if self.ips[i] == client then --- table.remove(self.ips, i) --- end --- end --- self.OnClientClosed:Fire(self, "Client Closed Connection!", client, client, ip) --- self.links[client] = nil -- lets clean up --- self:Destroy() --- end --- if data then --- if self.autoNormalization then --- data = net.denormalize(data) --- end --- if net.inList(self.bannedIPs, ip) then --- --print("We will ingore data from a banned client!") --- return --- end --- local hook = data:match("!(.-)!") --- self.OnDataRecieved:getConnection(hook):Fire(self, data, client, client, ip, self) --- if data:sub(1, 2) == "L!" then --- cList = data --- local list = {} --- for m, v in cList:gmatch("(%S-):(%S-)|") do --- list[m] = v --- end --- self.OnClientsModulesList:Fire(list, client, client, ip) --- end --- end --- end --- end) --- c.OnClientsModulesList = multi:newConnection() --- c.OnDataRecieved = multi:newConnection() --- c.OnClientClosed = multi:newConnection() --- c.OnClientConnected = multi:newConnection() --- return c --- end --- function net:newTCPServer(port) --- local c = {} --- local port = port or 0 --- c.tcp = assert(socket.bind("*", port)) --- c.tcp:settimeout(0) --- c.ip, c.port = c.tcp:getsockname() --- c.ips = {} --- if port == 0 then --- _, c.port = c.tcp:getsockname() --- end --- c.ids = {} --- c.bannedIPs = {} --- c.Type = "tcp" --- c.rMode = "*l" --- c.sMode = "*l" --- c.updaterRate = 1 --- c.autoNormalization = false --- c.updates = {} --- c.links = {} --- c.numspace = 4 --- c.broad = socket.udp() --- c.hostip = net.getLocalIP() --- function c:packMsg(data) --- local temp = bin.new() --- temp:addBlock(#data, self.numspace, "n") --- temp:addBlock(data) --- return temp:getData() --- end --- function c:enableBinaryMode() --- self.rMode = "b" --- self.sMode = "b" --- end --- function c:broadcast(name) --- table.insert( --- net.BroadcastDriver, --- function(loop, dt) --- self.broad:setoption("broadcast", true) --- self.broad:sendto(name .. "|" .. self.Type .. "|" .. self.hostip .. ":" .. self.port, "255.255.255.255", 11111) --- self.broad:setoption("broadcast", false) --- end --- ) --- end --- function c:setUpdateRate(n) --- self.updaterRate = n --- end --- function c:setReceiveMode(mode) --- self.rMode = mode --- end --- function c:setSendMode(mode) --- self.sMode = mode --- end --- function c:banCID(cid) --- --print("Function not supported on a tcp server!") --- end --- function c:banIP(ip) --- table.insert(self.bannedIPs, cid) --- end --- function c:send(handle, data) --- if self.autoNormalization then --- data = net.normalize(data) --- end --- if self.sMode == "*l" then --- handle:send(data .. "\n") --- elseif self.sMode == "b" then --- handle:send(self:packMsg(data)) --- else --- handle:send(data) --- end --- end --- function c:sendAllData(handle, data) --- if self.autoNormalization then --- data = net.normalize(data) --- end --- handle:send(data) --- end --- function c:pollClientModules(ip, port) --- self:send(ip, "L!", port) --- end --- function c:CIDFrom(ip, port) --- --print("Method not supported when using a TCP Server!") --- return "CIDs in TCP work differently!" --- end --- function c:sendAll(data) --- for i, v in pairs(self.ips) do --- self:send(v, data) --- end --- end --- function c:sendAllBut(data, cid) --- for i, v in pairs(self.ips) do --- if not (cid == i) then --- self:send(v, data) --- end --- end --- end --- function c:clientRegistered(cid) --- return self.ips[cid] --- end --- function c:clientLoggedIn(cid) --- return self.ips[cid] --- end --- function c:getUpdater(cid) --- return self.updates[cid] --- end --- function c:update() --- local client = self.tcp:accept(self.rMode) --- if not client then --- return --- end --- table.insert(self.ips, client) --- client:settimeout(0) --- client:setoption("keepalive", true) --- ip, port = client:getpeername() --- if ip and port then --- self.OnClientConnected:Fire(self, client, client, ip) --- multi:newThread("ServerClientHandler",function() --- while true do --- thread.skip(1) --- local data, err, dat, len --- if self.rMode == "b" then --- thread.hold( --- function() --- dat = client:receive(self.numspace) --- return dat --- end --- ) --- len = bin.new(dat):getBlock("n", self.numspace) --- data, err = client:receive(len) --- else --- data, err = client:receive(self.rMode) --- end --- if err == "closed" then --- for i = 1, #self.ips do --- if self.ips[i] == client then --- table.remove(self.ips, i) --- end --- end --- self.OnClientClosed:Fire(self, "Client Closed Connection!", client, client, ip) --- self.links[client] = nil -- lets clean up --- self:Destroy() --- thread.kill() --- end --- if data then --- if self.autoNormalization then --- data = net.denormalize(data) --- end --- if net.inList(self.bannedIPs, ip) then --- return --- end --- local hook = data:match("!(.-)!") --- self.OnDataRecieved:getConnection(hook):Fire(self, data, client, client, ip, self) --- if data:sub(1, 2) == "L!" then --- cList = data --- local list = {} --- for m, v in cList:gmatch("(%S-):(%S-)|") do --- list[m] = v --- end --- self.OnClientsModulesList:Fire(list, client, client, ip) --- end --- end --- end --- end) --- end --- end --- c.OnClientsModulesList = multi:newConnection() --- c.OnDataRecieved = multi:newConnection() --- c.OnClientClosed = multi:newConnection() --- c.OnClientConnected = multi:newConnection() --- table.insert(net.ConnectionDriver, c) --- net.OnServerCreated:Fire(c) --- return c --- end --- function net:newTCPClient(host, port) --- local c = {} --- c.ip = assert(socket.dns.toip(host)) --- c.tcp = socket.connect(c.ip, port) --- if not c.tcp then --- --print("Can't connect to the server: no response from server") --- return false --- end --- c.tcp:settimeout(0) --- --c.tcp:setoption('tcp-nodelay', true) --- c.tcp:setoption("keepalive", true) --- c.Type = "tcp" --- c.autoReconnect = true --- c.rMode = "*l" --- c.sMode = "*l" --- c.autoNormalization = false --- c.numspace = 4 --- function c:enableBinaryMode() --- self.rMode = "b" --- self.sMode = "b" --- end --- function c:setReceiveMode(mode) --- self.rMode = mode --- end --- function c:setSendMode(mode) --- self.sMode = mode --- end --- function c:packMsg(data) --- local temp = bin.new() --- temp:addBlock(#data, self.numspace) --- temp:addBlock(data) --- return temp:getData() --- end --- function c:send(data) --- if self.autoNormalization then --- data = net.normalize(data) --- end --- if self.sMode == "*l" then --- ind, err = self.tcp:send(data .. "\n") --- elseif self.sMode == "b" then --- ind, err = self.tcp:send(self:packMsg(data)) --- else --- ind, err = self.tcp:send(data) --- end --- if err == "closed" then --- self.OnClientDisconnected:Fire(self, err) --- elseif err == "timeout" then --- self.OnClientDisconnected:Fire(self, err) --- elseif err then --- --print(err) --- end --- end --- function c:sendRaw(data) --- if self.autoNormalization then --- data = net.normalize(data) --- end --- self.tcp:send(data) --- end --- function c:getCID() --- return "No Cid on a tcp client!" --- end --- function c:close() --- self.tcp:close() --- end --- function c:IDAssigned() --- return true --- end --- function c:update() --- if not self.tcp then --- return --- end --- local data, err, dat --- if self.rMode == "b" then --- thread.hold( --- function() --- dat = self.tcp:receive(self.numspace) --- return dat --- end --- ) --- len = bin.new(dat):getBlock("n", self.numspace) --- data, err = self.tcp:receive(len) --- else --- data, err = self.tcp:receive() --- end --- if err == "closed" then --- self.OnClientDisconnected:Fire(self, err) --- elseif err == "timeout" then --- self.OnClientDisconnected:Fire(self, err) --- elseif err then --- --print(err) --- end --- if data then --- if self.autoNormalization then --- data = net.denormalize(data) --- end --- local hook = data:match("!(.-)!") --- self.OnDataRecieved:getConnection(hook):Fire(self, data) --- end --- end --- function c:reconnect() --- multi:newFunction( --- function(func) --- self.tcp = socket.connect(self.ip, self.port) --- if self.tcp == nil then --- --print("Can't connect to the server: No response from server!") --- multi:newAlarm(3):OnRing( --- function(alarm) --- self:reconnect() --- alarm:Destroy() --- return --- end --- ):setName("net.timeoutTask") --- end --- self.OnConnectionRegained:Fire(self) --- self.tcp:settimeout(0) --- --self.tcp:setoption('tcp-nodelay', true) --- self.tcp:setoption("keepalive", true) --- end --- ) --- end --- c.event = --- multi:newEvent( --- function(event) --- return event.link:IDAssigned() --- end --- ):OnEvent( --- function(event) --- event.link.OnClientReady:Fire(event.link) --- event:Destroy() --- end --- ) --- c.event:setName("net.handshakeTask") --- c.event.link = c --- c.OnClientReady = multi:newConnection() --- c.OnClientDisconnected = multi:newConnection() --- c.OnDataRecieved = multi:newConnection() --- c.OnConnectionRegained = multi:newConnection() --- table.insert(net.ConnectionDriver, c) --- net.OnClientCreated:Fire(c) --- return c --- end --- net.timer = multi:newTimer():Start() --- multi:newThread( --- "ClientServerHandler", --- function() --- while true do --- thread.skip() --- for i = 1, #net.ConnectionDriver do --- thread.skip() --- net.ConnectionDriver[i]:update() --- end --- if net.timer:Get() >= 1 then --- for i = 1, #net.BroadcastDriver do --- net.BroadcastDriver[i]() --- end --- net.timer:Reset() --- end --- end --- end --- ) return net diff --git a/rockspec/lnet-5.0-0.rockspec b/rockspec/lnet-5.0-0.rockspec new file mode 100644 index 0000000..fa54930 --- /dev/null +++ b/rockspec/lnet-5.0-0.rockspec @@ -0,0 +1,25 @@ +package = "lnet" +version = "5.0-0" +source = { + url = "git://github.com/rayaman/net.git", + tag = "net-v5", +} +description = { + summary = "Lua networking library that wraps around lua-socket to make networking easy.", + detailed = [[ + This library uses the multi library. The new multitasking library and this one are now co-Dependant if using the networkManager integration for network parallelism. This has an event driven approach for networking which allows one to easily work async with the data. + ]], + homepage = "https://github.com/rayaman/net", + license = "MIT" +} +dependencies = { + "lua >= 5.1", + "luasocket" + "multi", +} +build = { + type = "builtin", + modules = { + ["net.init"] = "net/init.lua", + } +} \ No newline at end of file diff --git a/server.lua b/server.lua index 308bb2d..7181cbd 100644 --- a/server.lua +++ b/server.lua @@ -8,4 +8,7 @@ -- end) -- multi:mainloop() http = require("socket.http") -print(http.request("http://zjcdn.mangafox.me/store/manga/33769/091/compressed/s20210705_163050_598.jpg")) \ No newline at end of file +data, code, headers = http.request("http://zjcdn.mangafox.me/store/manga/33769/091.0/compressed/s20210705_163050_598.jpg") +for i,v in pairs(headers) do + print(i,v) +end \ No newline at end of file