在 Python 众多的 HTTP 客户端中,最有名的莫过于 、 和 。requests aiohttp httpx
在不借助其他第三方库的情况下, 只能发送同步请求; 只能发送异步请求; 既能发送同步请求,又能发送异步请求。requests aiohttp httpx
那么怎么选择呢
- 只发同步请求用 ,但可配合多线程变异步。
requests - 只发异步请求用 ,但可以配合await变同步。
aiohttp httpx 可以发同步请求也可以异步,但是请求速度同步略差于 ,异步略差于requests aiohttp
这里不建议使用多线程来做异步请求,建议使用异步IO的方式。
asyncio 的优势:
-
可以异步请求。 -
可以普通请求也可以作为WS客户端连接。 -
可以作为WEB服务器和WEBSOCKET服务器。 -
性能较好。
安装依赖
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6"><span style="color:#333333"><strong>pip</strong></span> install aiohttp
</span></span></span></span>
客户端
默认超时时间
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6">aiohttp.ClientTimeout(
total=<span style="color:#880000">5</span>*<span style="color:#880000">60</span>,
connect=<span style="color:#78a960">None</span>,
sock_connect=<span style="color:#78a960">None</span>,
sock_read=<span style="color:#78a960">None</span>
)
</span></span></span></span>
获取请求
基本请求
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6"><span style="color:#333333"><strong>import</strong></span> aiohttp
<span style="color:#333333"><strong>import</strong></span> asyncio
<span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>def</strong></span> <span style="color:#880000"><strong>main</strong></span>():
<span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>with</strong></span> aiohttp.ClientSession() <span style="color:#333333"><strong>as</strong></span> session:
params = {<span style="color:#880000">'key1'</span>: <span style="color:#880000">'value1'</span>, <span style="color:#880000">'key2'</span>: <span style="color:#880000">'value2'</span>}
resp = <span style="color:#333333"><strong>await</strong></span> session.get(
<span style="color:#880000">'https://www.psvmc.cn/login.json'</span>,
params=params
)
result = <span style="color:#333333"><strong>await</strong></span> resp.text()
result2 = <span style="color:#333333"><strong>await</strong></span> resp.json()
print(result)
print(result2)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
</span></span></span></span>
获取状态码
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6"><span style="color:#333333"><strong>import</strong></span> aiohttp
<span style="color:#333333"><strong>import</strong></span> asyncio
<span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>def</strong></span> <span style="color:#880000"><strong>main</strong></span>():
<span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>with</strong></span> aiohttp.ClientSession() <span style="color:#333333"><strong>as</strong></span> session:
params = {<span style="color:#880000">'key1'</span>: <span style="color:#880000">'value1'</span>, <span style="color:#880000">'key2'</span>: <span style="color:#880000">'value2'</span>}
<span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>with</strong></span> session.get(
<span style="color:#880000">'https://www.psvmc.cn/login.json'</span>,
params=params
)<span style="color:#333333"><strong>as</strong></span> resp:
print(resp.status)
print(<span style="color:#333333"><strong>await</strong></span> resp.text())
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
</span></span></span></span>
文件下载
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6"><span style="color:#333333"><strong>import</strong></span> aiohttp
<span style="color:#333333"><strong>import</strong></span> asyncio
<span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>def</strong></span> <span style="color:#880000"><strong>main</strong></span>():
<span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>with</strong></span> aiohttp.ClientSession() <span style="color:#333333"><strong>as</strong></span> session:
params = {<span style="color:#880000">'key1'</span>: <span style="color:#880000">'value1'</span>, <span style="color:#880000">'key2'</span>: <span style="color:#880000">'value2'</span>}
<span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>with</strong></span> session.get(
<span style="color:#880000">'https://www.psvmc.cn/search.json'</span>,
params=params
)<span style="color:#333333"><strong>as</strong></span> resp:
filename = <span style="color:#880000">"D://search.json"</span>
chunk_size = <span style="color:#880000">1000</span>
<span style="color:#333333"><strong>with</strong></span> open(filename, <span style="color:#880000">'wb'</span>) <span style="color:#333333"><strong>as</strong></span> fd:
<span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>for</strong></span> chunk <span style="color:#333333"><strong>in</strong></span> resp.content.iter_chunked(chunk_size):
fd.write(chunk)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
</span></span></span></span>
POST请求
基本用法
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6"><span style="color:#333333"><strong>import</strong></span> aiohttp
<span style="color:#333333"><strong>import</strong></span> asyncio
<span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>def</strong></span> <span style="color:#880000"><strong>main</strong></span>():
<span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>with</strong></span> aiohttp.ClientSession() <span style="color:#333333"><strong>as</strong></span> session:
resp = <span style="color:#333333"><strong>await</strong></span> session.post(
<span style="color:#880000">'https://www.psvmc.cn/login.json'</span>,
json={<span style="color:#880000">'keyword'</span>: <span style="color:#880000">'123'</span>}
)
result = <span style="color:#333333"><strong>await</strong></span> resp.text()
print(result)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
</span></span></span></span>
Form-encoded
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6"><span style="color:#333333"><strong>import</strong></span> aiohttp
<span style="color:#333333"><strong>import</strong></span> asyncio
<span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>def</strong></span> <span style="color:#880000"><strong>main</strong></span>():
<span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>with</strong></span> aiohttp.ClientSession() <span style="color:#333333"><strong>as</strong></span> session:
resp = <span style="color:#333333"><strong>await</strong></span> session.post(
<span style="color:#880000">'https://www.psvmc.cn/login.json'</span>,
data={<span style="color:#880000">'keyword'</span>: <span style="color:#880000">'123'</span>}
)
result = <span style="color:#333333"><strong>await</strong></span> resp.text()
print(result)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
</span></span></span></span>
Multipart-Encoded File
To upload Multipart-encoded files:
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6">url = <span style="color:#880000">'http://httpbin.org/post'</span>
<span style="color:#333333"><strong>files</strong></span> = {<span style="color:#880000">'file'</span>: <span style="color:#333333"><strong>open</strong></span>(<span style="color:#880000">'report.xls'</span>, <span style="color:#880000">'rb'</span>)}
await session.post(url, data=<span style="color:#333333"><strong>files</strong></span>)
</span></span></span></span>
You can set the?and?explicitly:?filename content_type
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6">url = <span style="color:#880000">'http://httpbin.org/post'</span>
<span style="color:#333333"><strong>data</strong></span> = FormData()
<span style="color:#333333"><strong>data</strong></span>.add_field(<span style="color:#880000">'file'</span>,
<span style="color:#333333"><strong>open</strong></span>(<span style="color:#880000">'report.xls'</span>, <span style="color:#880000">'rb'</span>),
filename=<span style="color:#880000">'report.xls'</span>,
content_type=<span style="color:#880000">'application/vnd.ms-excel'</span>)
await session.post(url, <span style="color:#333333"><strong>data</strong></span>=<span style="color:#333333"><strong>data</strong></span>)
</span></span></span></span>
Streaming uploads
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6"><span style="color:#333333"><strong>with</strong></span> open(<span style="color:#880000">"D://search.json"</span>, <span style="color:#880000">'rb'</span>) <span style="color:#333333"><strong>as</strong></span> f:
<span style="color:#333333"><strong>await</strong></span> session.post(<span style="color:#880000">'http://httpbin.org/post'</span>, data=f)
</span></span></span></span>
其它请求
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6"><span style="color:#333333"><strong>session</strong></span><span style="color:#880000">.put</span>(<span style="color:#880000">'http://httpbin.org/put'</span>, data=b<span style="color:#880000">'data'</span>)
<span style="color:#333333"><strong>session</strong></span><span style="color:#880000">.delete</span>(<span style="color:#880000">'http://httpbin.org/delete'</span>)
<span style="color:#333333"><strong>session</strong></span><span style="color:#880000">.head</span>(<span style="color:#880000">'http://httpbin.org/get'</span>)
<span style="color:#333333"><strong>session</strong></span><span style="color:#880000">.options</span>(<span style="color:#880000">'http://httpbin.org/get'</span>)
<span style="color:#333333"><strong>session</strong></span><span style="color:#880000">.patch</span>(<span style="color:#880000">'http://httpbin.org/patch'</span>, data=b<span style="color:#880000">'data'</span>)
</span></span></span></span>
WebSocket
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6"><span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>with</strong></span> session.ws_connect(<span style="color:#880000">'http://example.org/ws'</span>) <span style="color:#333333"><strong>as</strong></span> ws:
<span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>for</strong></span> msg <span style="color:#333333"><strong>in</strong></span> ws:
<span style="color:#333333"><strong>if</strong></span> msg.type == aiohttp.WSMsgType.TEXT:
<span style="color:#333333"><strong>if</strong></span> msg.data == <span style="color:#880000">'close cmd'</span>:
<span style="color:#333333"><strong>await</strong></span> ws.close()
<span style="color:#333333"><strong>break</strong></span>
<span style="color:#333333"><strong>else</strong></span>:
<span style="color:#333333"><strong>await</strong></span> ws.send_str(msg.data + <span style="color:#880000">'/answer'</span>)
<span style="color:#333333"><strong>elif</strong></span> msg.type == aiohttp.WSMsgType.ERROR:
<span style="color:#333333"><strong>break</strong></span>
</span></span></span></span>
发送消息
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6"><span style="color:#333333"><strong>await</strong></span> ws.send_str(<span style="color:#880000">'data'</span>)
</span></span></span></span>
服务端
WEB服务器
文本
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6"><span style="color:#333333"><strong>from</strong></span> aiohttp <span style="color:#333333"><strong>import</strong></span> web
<span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>def</strong></span> <span style="color:#880000"><strong>hello</strong></span>(request):
print(request.url)
<span style="color:#333333"><strong>return</strong></span> web.Response(text=<span style="color:#880000">"Hello, world"</span>)
app = web.Application()
app.add_routes([web.get(<span style="color:#880000">'/'</span>, hello)])
web.run_app(app, port=<span style="color:#880000">8080</span>)
</span></span></span></span>
注解
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6"><span style="color:#333333"><strong>from</strong></span> aiohttp <span style="color:#333333"><strong>import</strong></span> web
routes = web.RouteTableDef()
<span style="color:#1f7199">@routes.get('/')</span>
<span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>def</strong></span> <span style="color:#880000"><strong>hello</strong></span>(request):
print(request.url)
<span style="color:#333333"><strong>return</strong></span> web.Response(text=<span style="color:#880000">"Hello, world"</span>)
app = web.Application()
app.add_routes(routes)
web.run_app(app, port=<span style="color:#880000">8080</span>)
</span></span></span></span>
JSON
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6"><span style="color:#333333"><strong>from</strong></span> aiohttp <span style="color:#333333"><strong>import</strong></span> web
routes = web.RouteTableDef()
<span style="color:#1f7199">@routes.get('/')</span>
<span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>def</strong></span> <span style="color:#880000"><strong>hello</strong></span>(request):
print(request.url)
data = {<span style="color:#880000">'some'</span>: <span style="color:#880000">'data'</span>}
<span style="color:#333333"><strong>return</strong></span> web.json_response(data)
app = web.Application()
app.add_routes(routes)
web.run_app(app, port=<span style="color:#880000">8080</span>)
</span></span></span></span>
From参数获取
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6"><span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>def</strong></span> <span style="color:#880000"><strong>do_login</strong></span>(request):
data = <span style="color:#333333"><strong>await</strong></span> request.post()
username = data[<span style="color:#880000">'username'</span>]
password = data[<span style="color:#880000">'password'</span>]
</span></span></span></span>
文件上传服务
First, make sure that the HTML?element has its?enctype?attribute set to?.?<form> enctype="multipart/form-data"
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6"><<span style="color:#333333"><strong>form</strong></span> action=<span style="color:#880000">"/store/mp3"</span> method=<span style="color:#880000">"post"</span> accept-charset=<span style="color:#880000">"utf-8"</span>
enctype=<span style="color:#880000">"multipart/form-data"</span>>
<<span style="color:#333333"><strong>label</strong></span> for=<span style="color:#880000">"mp3"</span>>Mp3</<span style="color:#333333"><strong>label</strong></span>>
<<span style="color:#333333"><strong>input</strong></span> id=<span style="color:#880000">"mp3"</span> name=<span style="color:#880000">"mp3"</span> type=<span style="color:#880000">"file"</span> value=<span style="color:#880000">""</span>/>
<<span style="color:#333333"><strong>input</strong></span> type=<span style="color:#880000">"submit"</span> value=<span style="color:#880000">"submit"</span>/>
</<span style="color:#333333"><strong>form</strong></span>>
</span></span></span></span>
Then, in the?request handler?you can access the file input field as a?FileField?instance.
FileField?is simply a container for the file as well as some of its metadata:
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6"><span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>def</strong></span> <span style="color:#880000"><strong>store_mp3_handler</strong></span>(request):
<span style="color:#888888"># WARNING: don't do that if you plan to receive large files!</span>
data = <span style="color:#333333"><strong>await</strong></span> request.post()
mp3 = data[<span style="color:#880000">'mp3'</span>]
<span style="color:#888888"># .filename contains the name of the file in string format.</span>
filename = mp3.filename
<span style="color:#888888"># .file contains the actual file data that needs to be stored somewhere.</span>
mp3_file = data[<span style="color:#880000">'mp3'</span>].file
content = mp3_file.read()
<span style="color:#333333"><strong>return</strong></span> web.Response(
body=content,
headers={<span style="color:#880000">'CONTENT-DISPOSITION'</span>: mp3_file}
)
</span></span></span></span>
WebSockets
服务端
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6"><span style="color:#333333"><strong>import</strong></span> aiohttp
<span style="color:#333333"><strong>from</strong></span> aiohttp <span style="color:#333333"><strong>import</strong></span> web
routes = web.RouteTableDef()
<span style="color:#1f7199">@routes.get('/ws')</span>
<span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>def</strong></span> <span style="color:#880000"><strong>websocket_handler</strong></span>(request):
ws = web.WebSocketResponse()
<span style="color:#333333"><strong>await</strong></span> ws.prepare(request)
<span style="color:#333333"><strong>async</strong></span> <span style="color:#333333"><strong>for</strong></span> msg <span style="color:#333333"><strong>in</strong></span> ws:
<span style="color:#333333"><strong>if</strong></span> msg.type == aiohttp.WSMsgType.TEXT:
print(f<span style="color:#880000">"receive:{msg.data}"</span>)
<span style="color:#333333"><strong>if</strong></span> msg.data == <span style="color:#880000">'close'</span>:
<span style="color:#333333"><strong>await</strong></span> ws.close()
<span style="color:#333333"><strong>else</strong></span>:
<span style="color:#333333"><strong>await</strong></span> ws.send_str(<span style="color:#880000">"响应:"</span>+msg.data)
<span style="color:#333333"><strong>elif</strong></span> msg.type == aiohttp.WSMsgType.BINARY:
print(<span style="color:#880000">"receive:BINARY"</span>)
<span style="color:#333333"><strong>elif</strong></span> msg.type == aiohttp.WSMsgType.ERROR:
print(<span style="color:#880000">'ws connection closed with exception %s'</span> %
ws.exception())
print(<span style="color:#880000">'websocket connection closed'</span>)
<span style="color:#333333"><strong>return</strong></span> ws
app = web.Application()
app.add_routes(routes)
web.run_app(app, port=<span style="color:#880000">8888</span>)
</span></span></span></span>
客户端测试页面
页面
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6"><span style="color:#1f7199"><!DOCTYPE html></span>
<<span style="color:#333333"><strong>html</strong></span>>
<<span style="color:#333333"><strong>head</strong></span>>
<<span style="color:#333333"><strong>meta</strong></span> name=<span style="color:#880000">"viewport"</span> content=<span style="color:#880000">"width=device-width, initial-scale=1"</span> />
<<span style="color:#333333"><strong>title</strong></span>>聊天客户端</<span style="color:#333333"><strong>title</strong></span>>
</<span style="color:#333333"><strong>head</strong></span>>
<<span style="color:#333333"><strong>body</strong></span>>
<<span style="color:#333333"><strong>div</strong></span>>
<<span style="color:#333333"><strong>div</strong></span> id=<span style="color:#880000">"content"</span>></<span style="color:#333333"><strong>div</strong></span>>
<<span style="color:#333333"><strong>input</strong></span> type=<span style="color:#880000">"text"</span> style=<span style="color:#880000">"width: 100%"</span> id=<span style="color:#880000">"msg"</span> />
<<span style="color:#333333"><strong>button</strong></span> type=<span style="color:#880000">"button"</span> onclick=<span style="color:#880000">"emit()"</span>>发送</<span style="color:#333333"><strong>button</strong></span>>
</<span style="color:#333333"><strong>div</strong></span>>
<<span style="color:#333333"><strong>script</strong></span>
type=<span style="color:#880000">"text/javascript"</span>
src=<span style="color:#880000">"http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"</span>
></<span style="color:#333333"><strong>script</strong></span>>
<<span style="color:#333333"><strong>script</strong></span> type=<span style="color:#880000">"text/javascript"</span> src=<span style="color:#880000">"js/index.js"</span>></<span style="color:#333333"><strong>script</strong></span>>
</<span style="color:#333333"><strong>body</strong></span>>
</<span style="color:#333333"><strong>html</strong></span>>
</span></span></span></span>
断续器
<span style="color:#333333"><span style="background-color:#fefefe"><span style="color:#444444"><span style="background-color:#f6f6f6"><span style="color:#333333"><strong>var</strong></span> socket = <span style="color:#333333"><strong>new</strong></span> WebSocket(<span style="color:#880000">"ws://127.0.0.1:8888/ws"</span>);
$(<span style="color:#333333"><strong>function</strong></span> () {
listen();
})
<span style="color:#333333"><strong>function</strong></span> <span style="color:#880000"><strong>encodeScript</strong></span>(data) {
<span style="color:#333333"><strong>if</strong></span> (<span style="color:#78a960">null</span> == data || <span style="color:#880000">""</span> == data) {
<span style="color:#333333"><strong>return</strong></span> <span style="color:#880000">""</span>;
}
<span style="color:#333333"><strong>return</strong></span> data.replace(<span style="color:#880000">"<"</span>, <span style="color:#880000">"<"</span>).replace(<span style="color:#880000">">"</span>, <span style="color:#880000">">"</span>);
}
<span style="color:#333333"><strong>function</strong></span> <span style="color:#880000"><strong>emit</strong></span>() {
<span style="color:#333333"><strong>var</strong></span> text = encodeScript($(<span style="color:#880000">"#msg"</span>).val());
text = replace_em(text);
socket.send(text);
$(<span style="color:#880000">"#content"</span>).append(<span style="color:#880000">"<kbd style='color: #"</span> + <span style="color:#880000">"CECECE"</span> + <span style="color:#880000">"; font-size: "</span> + <span style="color:#880000">12</span> + <span style="color:#880000">";'>"</span> + text + <span style="color:#880000">"</kbd><br/>"</span>);
$(<span style="color:#880000">"#msg"</span>).val(<span style="color:#880000">""</span>);
}
<span style="color:#888888">//替换为HTML上的标签</span>
<span style="color:#333333"><strong>function</strong></span> <span style="color:#880000"><strong>replace_em</strong></span>(str) {
str = str.replace(<span style="color:#bc6060">/\</g</span>, <span style="color:#880000">'<'</span>);
str = str.replace(<span style="color:#bc6060">/\>/g</span>, <span style="color:#880000">'>'</span>);
str = str.replace(<span style="color:#bc6060">/\n/g</span>, <span style="color:#880000">'<br/>'</span>);
str = str.replace(<span style="color:#bc6060">/\[em_([0-9]*)\]/g</span>, <span style="color:#880000">'<img src="arclist/$1.gif" border="0" />'</span>);
<span style="color:#333333"><strong>return</strong></span> str;
};
<span style="color:#333333"><strong>function</strong></span> <span style="color:#880000"><strong>listen</strong></span>() {
socket.onopen = <span style="color:#333333"><strong>function</strong></span> () {
$(<span style="color:#880000">"#content"</span>).append(<span style="color:#880000">"<kbd>连接成功! 时间(s):"</span> + <span style="color:#397300">parseInt</span>(<span style="color:#333333"><strong>new</strong></span> <span style="color:#397300">Date</span>().getTime() / <span style="color:#880000">1000</span>) + <span style="color:#880000">"</kbd></br>"</span>);
heartCheck();
};
socket.onmessage = <span style="color:#333333"><strong>function</strong></span> (evt) {
$(<span style="color:#880000">"#content"</span>).append(evt.data + <span style="color:#880000">"</br>"</span>);
};
socket.onclose = <span style="color:#333333"><strong>function</strong></span> (evt) {
$(<span style="color:#880000">"#content"</span>).append(<span style="color:#880000">"<kbd>"</span> + <span style="color:#880000">"连接关闭! 时间(s):"</span> + <span style="color:#397300">parseInt</span>(<span style="color:#333333"><strong>new</strong></span> <span style="color:#397300">Date</span>().getTime() / <span style="color:#880000">1000</span>) + <span style="color:#880000">"</kbd></br>"</span>);
}
socket.onerror = <span style="color:#333333"><strong>function</strong></span> (evt) {
$(<span style="color:#880000">"#content"</span>).append(<span style="color:#880000">"<kbd>"</span> + <span style="color:#880000">"ERROR!"</span> + <span style="color:#880000">"</kbd></br>"</span>);
}
}
<span style="color:#888888">//心跳包</span>
<span style="color:#333333"><strong>function</strong></span> <span style="color:#880000"><strong>heartCheck</strong></span>() {
setInterval(<span style="color:#333333"><strong>function</strong></span> () {
<span style="color:#333333"><strong>if</strong></span> (socket) {
<span style="color:#333333"><strong>let</strong></span> buffer = <span style="color:#333333"><strong>new</strong></span> <span style="color:#397300">ArrayBuffer</span>(<span style="color:#880000">2</span>); <span style="color:#888888">// 初始化14个Byte的二进制数据缓冲区</span>
<span style="color:#333333"><strong>let</strong></span> dataView = <span style="color:#333333"><strong>new</strong></span> <span style="color:#397300">DataView</span>(buffer);
dataView.setInt16(<span style="color:#880000">0</span>, <span style="color:#880000">1</span>);
socket.send(dataView);
<span style="color:#397300">console</span>.info(<span style="color:#880000">"发送心跳"</span>, <span style="color:#880000">" 时间(s):"</span> + <span style="color:#397300">parseInt</span>(<span style="color:#333333"><strong>new</strong></span> <span style="color:#397300">Date</span>().getTime() / <span style="color:#880000">1000</span>));
}
}, <span style="color:#880000">30000</span>);
}
<span style="color:#397300">document</span>.onkeydown = <span style="color:#333333"><strong>function</strong></span> (event) {
<span style="color:#333333"><strong>var</strong></span> e = event || <span style="color:#397300">window</span>.event || <span style="color:#397300">arguments</span>.callee.caller.arguments[<span style="color:#880000">0</span>];
<span style="color:#333333"><strong>if</strong></span> (e && e.keyCode == <span style="color:#880000">13</span>) { <span style="color:#888888">// enter 键</span>
emit();
}
};</span></span></span></span>
|