Skip to content

Instantly share code, notes, and snippets.

@minism
Created September 7, 2012 06:41
Show Gist options
  • Save minism/3663900 to your computer and use it in GitHub Desktop.
Save minism/3663900 to your computer and use it in GitHub Desktop.
local binary = require 'shared.binary'
-- Datagram format
--
-- uint32 seq Sequence number of the packet
-- uint32 ack Last acknowledged sequence number of remote channel
-- uint16 fragment_ofs Offset of fragment
-- uint16 fragment_len Length of fragment, zero if single message
-- uint8 cmd Command (see command.lua)
--- binary data Arbitrary data
-- Packet settings
local UDP_PACKETSIZE = 1500
local HEADER_SIZE = 13
local BODY_SIZE = UDP_PACKETSIZE - 13
local datagram = {
BODY_SIZE = BODY_SIZE
}
function datagram.pack(seq, ack, fragment_ofs, fragment_len, cmd, data)
local buf = {}
table.insert(buf, binary.encode_uint32(seq))
table.insert(buf, binary.encode_uint32(ack))
table.insert(buf, binary.encode_uint16(fragment_ofs))
table.insert(buf, binary.encode_uint16(fragment_len))
table.insert(buf, binary.encode_uint8(cmd))
table.insert(buf, data)
return table.concat(buf)
end
function datagram.unpack(datagram)
local seq = binary.decode_uint32(string.sub(datagram, 1, 4))
local ack = binary.decode_uint32(string.sub(datagram, 5, 8))
local fragment_ofs = binary.decode_uint16(string.sub(datagram, 9, 10))
local fragment_len = binary.decode_uint16(string.sub(datagram, 11, 12))
local cmd = binary.decode_uint8(string.sub(datagram, 13, 13))
local data = string.sub(datagram, DGRAM_HEADER_SIZE + 1)
end
return datagram
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment