PageRenderTime 115ms CodeModel.GetById 67ms app.highlight 8ms RepoModel.GetById 37ms app.codeStats 0ms

/lualib/socket.lua

https://github.com/RainVision/skynet
Lua | 79 lines | 66 code | 13 blank | 0 comment | 8 complexity | b0c430b6ee55eb4e0bb00b5a6ed0f0f7 MD5 | raw file
 1local skynet = require "skynet"
 2local c = require "socket.c"
 3
 4local socket = {}
 5local fd
 6local object
 7local data = {}
 8
 9local function presend()
10	if next(data) then
11		local tmp = data
12		data = {}
13		for _,v in ipairs(tmp) do
14			socket.write(fd, v)
15		end
16	end
17end
18
19function socket.connect(addr)
20	local ip, port = string.match(addr,"([^:]+):(.+)")
21	port = tonumber(port)
22	socket.close()
23	fd = c.open(ip,port)
24	if fd == nil then
25		return true
26	end
27	skynet.send(".connection", "text", "ADD", fd , skynet.address(skynet.self()))
28	object = c.new()
29	presend()
30end
31
32function socket.stdin()
33	skynet.send(".connection", "text", "ADD", 1 , skynet.address(skynet.self()))
34	object = c.new()
35end
36
37function socket.push(msg,sz)
38	if msg then
39		c.push(object, msg, sz)
40	end
41end
42
43function socket.read(bytes)
44	return c.read(object, bytes)
45end
46
47function socket.readline(sep)
48	return c.readline(object, sep)
49end
50
51function socket.readblock(...)
52	return c.readblock(object,...)
53end
54
55function socket.write(...)
56	local str = c.write(fd, ...)
57	if str then
58		socket.close()
59		table.insert(data, str)
60	end
61end
62
63function socket.writeblock(...)
64	local str = c.writeblock(fd, ...)
65	if str then
66		socket.close()
67		table.insert(data, str)
68	end
69end
70
71function socket.close()
72	if fd then
73		skynet.send(".connection","text", "DEL", fd)
74		fd = nil
75	end
76end
77
78return socket
79