IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 系统运维 -> Python网络请求-aiohttp -> 正文阅读

[系统运维]Python网络请求-aiohttp

在 Python 众多的 HTTP 客户端中,最有名的莫过于 、 和 。requestsaiohttphttpx

在不借助其他第三方库的情况下, 只能发送同步请求; 只能发送异步请求; 既能发送同步请求,又能发送异步请求。requestsaiohttphttpx

那么怎么选择呢

  • 只发同步请求用 ,但可配合多线程变异步。requests
  • 只发异步请求用 ,但可以配合await变同步。aiohttp
  • httpx可以发同步请求也可以异步,但是请求速度同步略差于 ,异步略差于requestsaiohttp

这里不建议使用多线程来做异步请求,建议使用异步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:?filenamecontent_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>
  系统运维 最新文章
配置小型公司网络WLAN基本业务(AC通过三层
如何在交付运维过程中建立风险底线意识,提
快速传输大文件,怎么通过网络传大文件给对
从游戏服务端角度分析移动同步(状态同步)
MySQL使用MyCat实现分库分表
如何用DWDM射频光纤技术实现200公里外的站点
国内顺畅下载k8s.gcr.io的镜像
自动化测试appium
ctfshow ssrf
Linux操作系统学习之实用指令(Centos7/8均
上一篇文章      下一篇文章      查看所有文章
加:2021-11-27 10:18:21  更:2021-11-27 10:20:11 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/16 1:36:34-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码