加入我们,或者,欢迎回来。
您需要 登录 才可以下载或查看,没有帐号?注册会员
x
本帖最后由 guoxiaomi 于 2018-12-27 15:52 编辑
MV本来就是浏览器,原生支持websocket,但是 XP/VX/VA 目前没有看到类似的东西。这里就提供一个吧。
来自 github 上的 https://github.com/dhbaird/easywsclient,MIT Lisenece。据说作者写的时候没考虑到有人会在windows下用g++编译,所以“找了”大神帮忙修改了一点点,最后的源代码如下:
20181227-websocket.zip
(374.9 KB, 下载次数: 114)
2018/12/27 更新3:
1. 解决了无法正常关闭 websocket 连接的问题
2. 提供了有限功能的XP范例,见 4 楼
2018/11/26 更新2:
1. 现在可以同时开启多个 websocket 连接,测试代码见 main.rb
2. update同时返回 总字符串长度 * 1024 + 接受的信息条数,从而同时得到这两个数据
3. ws_data 不需要接受参数,会获取前一个 ws_update(index) 返回的数据
2018/11/26 更新:解决了之前版本丢包问题
其中 main.cpp 是我自己随便写的封装。编译:
- g++ .\main.cpp .\easywsclient.cpp -shared -lws2_32 -o websocket.dll
复制代码
将 libgcc_s_dw2-1.dll 和 libstdc++-6.dll 一起附上了
发现还要 libwinpthread-1.dll
下面是测试代码,ws_url 里是一个 echo 服务器:
ws_url = "ws://demos.kaazing.com/echo" DLL_PATH = "../websocket.dll" WS_CONNECT = Win32API.new(DLL_PATH, "ws_connect", "ip", "i") WS_UPDATE = Win32API.new(DLL_PATH, "ws_update", "i", "i") WS_DATA = Win32API.new(DLL_PATH, "ws_data", "pp", "v") WS_SEND = Win32API.new(DLL_PATH, "ws_send", "ip", "v") WS_CLOSE = Win32API.new(DLL_PATH, "ws_close", "i", "v") raise if WS_CONNECT.call(0, ws_url) < 0 f = File.open("../result.txt", "w") 30.times do |i| WS_SEND.call(0, "hi! #{i}") end 120.times do |i| Graphics.update n = WS_UPDATE.call(0) buffer_len = n / 1024 recv_num = n % 1024 if recv_num > 0 buffer = "\0" * buffer_len lens = "\0" * 4 * recv_num WS_DATA.call(buffer, lens) s = 0 f.puts "recv #{recv_num} at frame No.#{i}:" lens.unpack("L*").each do |len| f.puts "#{buffer[s...s + len]}" s += len end end end WS_CLOSE.call(0) f.close exit
ws_url = "ws://demos.kaazing.com/echo"
DLL_PATH = "../websocket.dll"
WS_CONNECT = Win32API.new(DLL_PATH, "ws_connect", "ip", "i")
WS_UPDATE = Win32API.new(DLL_PATH, "ws_update", "i", "i")
WS_DATA = Win32API.new(DLL_PATH, "ws_data", "pp", "v")
WS_SEND = Win32API.new(DLL_PATH, "ws_send", "ip", "v")
WS_CLOSE = Win32API.new(DLL_PATH, "ws_close", "i", "v")
raise if WS_CONNECT.call(0, ws_url) < 0
f = File.open("../result.txt", "w")
30.times do |i|
WS_SEND.call(0, "hi! #{i}")
end
120.times do |i|
Graphics.update
n = WS_UPDATE.call(0)
buffer_len = n / 1024
recv_num = n % 1024
if recv_num > 0
buffer = "\0" * buffer_len
lens = "\0" * 4 * recv_num
WS_DATA.call(buffer, lens)
s = 0
f.puts "recv #{recv_num} at frame No.#{i}:"
lens.unpack("L*").each do |len|
f.puts "#{buffer[s...s + len]}"
s += len
end
end
end
WS_CLOSE.call(0)
f.close
exit
生成结果,注意到 websocket 会一口气收到大量信息,并且顺序可能是乱序的,其实跟网速什么的有关系:
recv 15 at frame No.9: hi! 0 hi! 1 hi! 2 hi! 3 hi! 4 hi! 5 hi! 6 hi! 7 hi! 8 hi! 9 hi! 10 hi! 11 hi! 12 hi! 13 hi! 14 recv 15 at frame No.17: hi! 15 hi! 16 hi! 17 hi! 18 hi! 19 hi! 20 hi! 21 hi! 22 hi! 23 hi! 24 hi! 25 hi! 26 hi! 27 hi! 28 hi! 29
recv 15 at frame No.9:
hi! 0
hi! 1
hi! 2
hi! 3
hi! 4
hi! 5
hi! 6
hi! 7
hi! 8
hi! 9
hi! 10
hi! 11
hi! 12
hi! 13
hi! 14
recv 15 at frame No.17:
hi! 15
hi! 16
hi! 17
hi! 18
hi! 19
hi! 20
hi! 21
hi! 22
hi! 23
hi! 24
hi! 25
hi! 26
hi! 27
hi! 28
hi! 29
|