-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
Copy pathsimplewebsocket.lua
executable file
·95 lines (84 loc) · 2.88 KB
/
simplewebsocket.lua
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
local skynet = require "skynet"
local socket = require "skynet.socket"
local service = require "skynet.service"
local websocket = require "http.websocket"
local handle = {}
local MODE = ...
if MODE == "agent" then
function handle.connect(id)
print("ws connect from: " .. tostring(id))
end
function handle.handshake(id, header, url)
local addr = websocket.addrinfo(id)
print("ws handshake from: " .. tostring(id), "url", url, "addr:", addr)
print("----header-----")
for k,v in pairs(header) do
print(k,v)
end
print("--------------")
end
function handle.message(id, msg, msg_type)
assert(msg_type == "binary" or msg_type == "text")
websocket.write(id, msg)
end
function handle.ping(id)
print("ws ping from: " .. tostring(id) .. "\n")
end
function handle.pong(id)
print("ws pong from: " .. tostring(id))
end
function handle.close(id, code, reason)
print("ws close from: " .. tostring(id), code, reason)
end
function handle.error(id)
print("ws error from: " .. tostring(id))
end
skynet.start(function ()
skynet.dispatch("lua", function (_,_, id, protocol, addr)
local ok, err = websocket.accept(id, handle, protocol, addr)
if not ok then
print(err)
end
end)
end)
else
local function simple_echo_client_service(protocol)
local skynet = require "skynet"
local websocket = require "http.websocket"
local url = string.format("%s://127.0.0.1:9948/test_websocket", protocol)
local ws_id = websocket.connect(url)
while true do
local msg = "hello world!"
websocket.write(ws_id, msg)
print(">: " .. msg)
local resp, close_reason = websocket.read(ws_id)
print("<: " .. (resp and resp or "[Close] " .. close_reason))
if not resp then
print("echo server close.")
break
end
websocket.ping(ws_id)
skynet.sleep(100)
end
end
skynet.start(function ()
local agent = {}
for i= 1, 20 do
agent[i] = skynet.newservice(SERVICE_NAME, "agent")
end
local balance = 1
local protocol = "ws"
local id = socket.listen("0.0.0.0", 9948)
skynet.error(string.format("Listen websocket port 9948 protocol:%s", protocol))
socket.start(id, function(id, addr)
print(string.format("accept client socket_id: %s addr:%s", id, addr))
skynet.send(agent[balance], "lua", id, protocol, addr)
balance = balance + 1
if balance > #agent then
balance = 1
end
end)
-- test echo client
service.new("websocket_echo_client", simple_echo_client_service, protocol)
end)
end