Blame view

publish/skynet/service/gate.lua 2.14 KB
4d6f285d   zhouhaihai   增加发布功能
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
  local skynet = require "skynet"
  local gateserver = require "snax.gateserver"
  
  local watchdog
  local connection = {}	-- fd -> connection : { fd , client, agent , ip, mode }
  local forwarding = {}	-- agent -> connection
  
  skynet.register_protocol {
  	name = "client",
  	id = skynet.PTYPE_CLIENT,
  }
  
  local handler = {}
  
  function handler.open(source, conf)
  	watchdog = conf.watchdog or source
  end
  
  function handler.message(fd, msg, sz)
  	-- recv a package, forward it
  	local c = connection[fd]
  	local agent = c.agent
  	if agent then
  		-- It's safe to redirect msg directly , gateserver framework will not free msg.
  		skynet.redirect(agent, c.client, "client", fd, msg, sz)
  	else
  		skynet.send(watchdog, "lua", "socket", "data", fd, skynet.tostring(msg, sz))
  		-- skynet.tostring will copy msg to a string, so we must free msg here.
  		skynet.trash(msg,sz)
  	end
  end
  
  function handler.connect(fd, addr)
  	local c = {
  		fd = fd,
  		ip = addr,
  	}
  	connection[fd] = c
  	skynet.send(watchdog, "lua", "socket", "open", fd, addr)
  end
  
  local function unforward(c)
  	if c.agent then
  		forwarding[c.agent] = nil
  		c.agent = nil
  		c.client = nil
  	end
  end
  
  local function close_fd(fd)
  	local c = connection[fd]
  	if c then
  		unforward(c)
  		connection[fd] = nil
  	end
  end
  
  function handler.disconnect(fd)
  	close_fd(fd)
  	skynet.send(watchdog, "lua", "socket", "close", fd)
  end
  
  function handler.error(fd, msg)
  	close_fd(fd)
  	skynet.send(watchdog, "lua", "socket", "error", fd, msg)
  end
  
  function handler.warning(fd, size)
  	skynet.send(watchdog, "lua", "socket", "warning", fd, size)
  end
  
  local CMD = {}
  
  function CMD.forward(source, fd, client, address)
  	local c = assert(connection[fd])
  	unforward(c)
  	c.client = client or 0
  	c.agent = address or source
  	forwarding[c.agent] = c
  	gateserver.openclient(fd)
  end
  
  function CMD.accept(source, fd)
  	local c = assert(connection[fd])
  	unforward(c)
  	gateserver.openclient(fd)
  end
  
  function CMD.kick(source, fd)
  	gateserver.closeclient(fd)
  end
  
  function CMD.forcekick(source, fd)
  	gateserver.closeclient(fd)
  	skynet.send(watchdog, "lua", "forceClose", fd)
  end
  
  function handler.command(cmd, source, ...)
  	local f = assert(CMD[cmd])
  	return f(source, ...)
  end
  
  gateserver.start(handler)