Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require("glsock")
- oohh = oohh or {}
- oohh.Ip = me:IPAddress():match("(.-):")
- oohh.ServerPort = 5556
- oohh.ClientPort = 27005
- oohh.Hooks = oohh.Hooks or {}
- function oohh.Hook(tag, callback)
- oohh.Hooks[tag] = callback
- end
- local function decode(str)
- local args = sigh.Decode(str)
- local id = args[1]
- table.remove(args, 1)
- return id, args
- end
- local function encode(id, ...)
- return sigh.Encode(id, ...)
- end
- function oohh.Send(id, ...)
- local str = encode(id, ...)
- oohh.RawSend(str)
- end
- function oohh.ReceiveFromoohh(str)
- local id, args = decode(str)
- if oohh.Hooks[id] then
- oohh.Hooks[id](unpack(args))
- end
- end
- hook.Add("OohhMessage", "oohh", oohh.ReceiveFromoohh)
- -- socket specific code
- function oohh.RawSend(str)
- if oohh_client then
- oohh_client:Cancel()
- oohh_client:Close()
- end
- oohh_client = GLSock(GLSOCK_TYPE_TCP)
- oohh_client:Connect(oohh.Ip, oohh.ClientPort, function(sck, error)
- if error == GLSOCK_ERROR_SUCCESS then
- local buffer = GLSockBuffer()
- buffer:Write(str)
- buffer:Write("\n")
- sck:Send(buffer, function() end)
- else
- print("Failed to connect to capsadmin, error: " .. error)
- end
- end)
- end
- function oohh.StartServer()
- local bind_socket
- local function OnRead(sck, buffer, error)
- if error == GLSOCK_ERROR_SUCCESS then
- local count, data = buffer:Read(buffer:Size())
- if count > 0 then
- hook.Call("OohhMessage", GAMEMODE, data)
- end
- end
- if error == GLSOCK_ERROR_SUCCESS then
- bind_socket()
- else
- sck:Read(100, OnRead)
- end
- end
- local function OnAccept(sck, client, errno)
- if errno == GLSOCK_ERROR_SUCCESS then
- client:Read(1500, OnRead)
- else
- print("Accept Error: "..tonumber(errno))
- end
- end
- local function OnListen(sck, errno)
- if errno == GLSOCK_ERROR_SUCCESS then
- sck:Accept(OnAccept)
- else
- print("Listen Error: "..tonumber(errno))
- end
- end
- local function OnBind(sck, errno)
- print(sck, errno)
- if errno == GLSOCK_ERROR_SUCCESS then
- sck:Listen(10, OnListen)
- print("bound to port " .. oohh.ServerPort)
- else
- print("Bind Error: "..tonumber(errno))
- end
- end
- bind_socket = function()
- if oohh_server then
- oohh_server:Cancel()
- oohh_server:Close()
- oohh_server:Destroy()
- end
- oohh_server = GLSock(GLSOCK_TYPE_ACCEPTOR)
- oohh_server:Bind("", oohh.ServerPort, OnBind)
- end
- bind_socket()
- end
- oohh.StartServer()
- oohh.Hook("hello", function(...)
- print(...)
- end)
- oohh.Send("hello", "hello from gmod!")
Advertisement
Add Comment
Please, Sign In to add comment