Last active
December 17, 2016 15:28
-
-
Save marcogravbrot/f63698fc096a3cc667f8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SENDING_DATA = false | |
function net.SendChunk(id, data, ply, callback, max, rate) | |
max = max or (2^16-2^10)-1 | |
rate = rate or 1/4 | |
assert(not SENDING_DATA) | |
SENDING_DATA = true | |
local chunk_count = math.ceil(string.len(data) / max) | |
net.Start(id) | |
net.WriteInt(chunk_count, 32) | |
if ply and SERVER then | |
net.Send(ply) | |
elseif SERVER then | |
net.Broadcast() | |
elseif CLIENT then | |
net.SendToServer() | |
end | |
for i = 1, chunk_count do | |
local delay = rate * ( i - 1 ) | |
timer.Simple(delay, function() | |
local chunk = string.sub(data, ( i - 1 ) * max + 1, i * max) | |
local chunk_len = string.len(chunk) | |
net.Start(id) | |
net.WriteData(chunk, chunk_len) | |
net.WriteBit(i == chunk_count) | |
if ply and SERVER then | |
net.Send(ply) | |
elseif SERVER then | |
net.Broadcast() | |
elseif CLIENT then | |
net.SendToServer() | |
end | |
if callback then | |
callback(chunk_count, i) | |
end | |
if i == chunk_count then | |
SENDING_DATA = false | |
end | |
end) | |
end | |
end | |
function net.ReceiveChunk(id, func, callback) | |
local chunks = chunks or {} | |
local counted = false | |
local count | |
net.Receive(id, function(len, server) | |
if not counted then | |
count = net.ReadInt(32) | |
if count then | |
counted = true | |
return | |
end | |
end | |
local chunk = net.ReadData(( len - 1 ) / 8) | |
local last_chunk = net.ReadBit() == 1 | |
if callback then | |
callback(count, #chunks+1) | |
end | |
table.insert(chunks, chunk) | |
if last_chunk then | |
local data = table.concat(chunks) | |
func(data, server) | |
chunks = {} | |
counted = false | |
count = nil | |
end | |
end) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment