SlideShare a Scribd company logo
1 of 24
Download to read offline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# client.py
import socket
s = socket.create_connection(('localhost', 8000))
while True:
data = input('>> ')
s.send(data.encode())
data = s.recv(1024)
print(data)
# server.py
import socket
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('localhost', 8000))
s.listen(100)
while True:
client, __ = s.accept()
data = client.recv(1024)
while data:
client.send(data)
data = client.recv(1024)
client.close()
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
# simple_http.py
from BaseHTTPServer import BaseHTTPRequestHandler,
HTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write("Hello World".encode('utf8'))
HTTPServer(('localhost', 8000), Handler).serve_forever()
Thread Stats Avg Stdev Max +/- Stdev
Latency 9.94s 21.79s 1.45m 83.49%
Req/Sec 0.03 1.92 111.00 99.97%
703 requests in 1.67m, 70.71KB read
Socket errors: connect 0, read 32, write 0, timeout
4604
Requests/sec: 7.03
Transfer/sec: 723.95B
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
# threaded_http.py
from BaseHTTPServer import BaseHTTPRequestHandler,
HTTPServer
from SocketServer import ThreadingMixIn
class ThreadServer(ThreadingMixIn, HTTPServer):
pass
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write("Hello World".encode('utf8'))
ThreadServer(('localhost', 8000), Handler).serve_forever()
Thread Stats Avg Stdev Max +/- Stdev
Latency 9.94s 21.79s 1.45m 83.49%
Req/Sec 0.03 1.92 111.00 99.97%
703 requests in 1.67m, 70.71KB read
Socket errors: connect 0, read 32, write 0, timeout
4604
Requests/sec: 7.03
Transfer/sec: 723.95B
Thread Stats Avg Stdev Max +/- Stdev
Latency 215.55ms 740.19ms 7.41s 92.21%
Req/Sec 1.01 9.51 666.00 98.71%
10052 requests in 1.67m, 0.99MB read
Socket errors: connect 0, read 0, write 0, timeout 344
Requests/sec: 100.50
Transfer/sec: 10.11KB
import asyncio
@asyncio.coroutine
def handle_echo(reader, writer):
data = yield from reader.read(100)
while data:
writer.write(data.decode())
yield from writer.drain()
data = yield from reader.read(100)
writer.close()
try:
loop = asyncio.get_event_loop()
coro = asyncio.start_server(handle_echo, '127.0.0.1', 8000, loop=loop)
server = loop.run_until_complete(coro)
loop.run_forever()
except:
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import asyncio
async def handle_echo(reader, writer):
data = await reader.read(100)
while data:
writer.write(data)
await writer.drain()
data = await reader.read(100)
writer.close()
try:
loop = asyncio.get_event_loop()
coro = asyncio.start_server(handle_echo, '127.0.0.1', 8000, loop=loop)
server = loop.run_until_complete(coro)
loop.run_forever()
except:
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
3.5
1. Compatibilidade entre bibliotecas
2. Útil para aplicações IO bound ou com
muitas conexões abertas mas sem
processamento
3. Pode ser mais dificil de programar
4. Starvation
gevent

More Related Content

What's hot

Programa donde suma las filass de las dos columna y ordena el resultado de l...
Programa donde suma  las filass de las dos columna y ordena el resultado de l...Programa donde suma  las filass de las dos columna y ordena el resultado de l...
Programa donde suma las filass de las dos columna y ordena el resultado de l...
Yo no soy perfecta pero soy mejor que tu
 
Ogdc 2013 lets remake the wheel
Ogdc 2013 lets remake the wheelOgdc 2013 lets remake the wheel
Ogdc 2013 lets remake the wheel
Son Aris
 

What's hot (20)

The Ring programming language version 1.5.2 book - Part 49 of 181
The Ring programming language version 1.5.2 book - Part 49 of 181The Ring programming language version 1.5.2 book - Part 49 of 181
The Ring programming language version 1.5.2 book - Part 49 of 181
 
Асинхронность и многопоточность в Яндекс.Такси — Дмитрий Курилов
Асинхронность и многопоточность в Яндекс.Такси — Дмитрий КуриловАсинхронность и многопоточность в Яндекс.Такси — Дмитрий Курилов
Асинхронность и многопоточность в Яндекс.Такси — Дмитрий Курилов
 
A promise is a Promise
A promise is a PromiseA promise is a Promise
A promise is a Promise
 
Programa donde suma las filass de las dos columna y ordena el resultado de l...
Programa donde suma  las filass de las dos columna y ordena el resultado de l...Programa donde suma  las filass de las dos columna y ordena el resultado de l...
Programa donde suma las filass de las dos columna y ordena el resultado de l...
 
The Ring programming language version 1.5.1 book - Part 48 of 180
The Ring programming language version 1.5.1 book - Part 48 of 180The Ring programming language version 1.5.1 book - Part 48 of 180
The Ring programming language version 1.5.1 book - Part 48 of 180
 
The Ring programming language version 1.5.1 book - Part 60 of 180
The Ring programming language version 1.5.1 book - Part 60 of 180The Ring programming language version 1.5.1 book - Part 60 of 180
The Ring programming language version 1.5.1 book - Part 60 of 180
 
Parallel Computing With Dask - PyDays 2017
Parallel Computing With Dask - PyDays 2017Parallel Computing With Dask - PyDays 2017
Parallel Computing With Dask - PyDays 2017
 
The Ring programming language version 1.5.4 book - Part 53 of 185
The Ring programming language version 1.5.4 book - Part 53 of 185The Ring programming language version 1.5.4 book - Part 53 of 185
The Ring programming language version 1.5.4 book - Part 53 of 185
 
The Ring programming language version 1.4 book - Part 18 of 30
The Ring programming language version 1.4 book - Part 18 of 30The Ring programming language version 1.4 book - Part 18 of 30
The Ring programming language version 1.4 book - Part 18 of 30
 
The Ring programming language version 1.5.4 book - Part 65 of 185
The Ring programming language version 1.5.4 book - Part 65 of 185The Ring programming language version 1.5.4 book - Part 65 of 185
The Ring programming language version 1.5.4 book - Part 65 of 185
 
The Ring programming language version 1.2 book - Part 41 of 84
The Ring programming language version 1.2 book - Part 41 of 84The Ring programming language version 1.2 book - Part 41 of 84
The Ring programming language version 1.2 book - Part 41 of 84
 
The Ring programming language version 1.8 book - Part 69 of 202
The Ring programming language version 1.8 book - Part 69 of 202The Ring programming language version 1.8 book - Part 69 of 202
The Ring programming language version 1.8 book - Part 69 of 202
 
The Ring programming language version 1.10 book - Part 70 of 212
The Ring programming language version 1.10 book - Part 70 of 212The Ring programming language version 1.10 book - Part 70 of 212
The Ring programming language version 1.10 book - Part 70 of 212
 
The Ring programming language version 1.5.2 book - Part 64 of 181
The Ring programming language version 1.5.2 book - Part 64 of 181The Ring programming language version 1.5.2 book - Part 64 of 181
The Ring programming language version 1.5.2 book - Part 64 of 181
 
The Ring programming language version 1.3 book - Part 49 of 88
The Ring programming language version 1.3 book - Part 49 of 88The Ring programming language version 1.3 book - Part 49 of 88
The Ring programming language version 1.3 book - Part 49 of 88
 
OGDC2013_Lets remake the wheel_ Mr Nguyen Trung Hung
OGDC2013_Lets remake the wheel_ Mr Nguyen Trung HungOGDC2013_Lets remake the wheel_ Mr Nguyen Trung Hung
OGDC2013_Lets remake the wheel_ Mr Nguyen Trung Hung
 
Ogdc 2013 lets remake the wheel
Ogdc 2013 lets remake the wheelOgdc 2013 lets remake the wheel
Ogdc 2013 lets remake the wheel
 
The Ring programming language version 1.3 book - Part 50 of 88
The Ring programming language version 1.3 book - Part 50 of 88The Ring programming language version 1.3 book - Part 50 of 88
The Ring programming language version 1.3 book - Part 50 of 88
 
The Ring programming language version 1.9 book - Part 78 of 210
The Ring programming language version 1.9 book - Part 78 of 210The Ring programming language version 1.9 book - Part 78 of 210
The Ring programming language version 1.9 book - Part 78 of 210
 
The Ring programming language version 1.2 book - Part 48 of 84
The Ring programming language version 1.2 book - Part 48 of 84The Ring programming language version 1.2 book - Part 48 of 84
The Ring programming language version 1.2 book - Part 48 of 84
 

Viewers also liked

Viewers also liked (8)

Cloud computing
Cloud computingCloud computing
Cloud computing
 
Scrum Gathering Rio 2014 - Melhorando sua Estratégia de Testes Automatizados
Scrum Gathering Rio 2014 - Melhorando sua Estratégia de Testes AutomatizadosScrum Gathering Rio 2014 - Melhorando sua Estratégia de Testes Automatizados
Scrum Gathering Rio 2014 - Melhorando sua Estratégia de Testes Automatizados
 
O que é ser um bom programador?
O que é ser um bom programador?O que é ser um bom programador?
O que é ser um bom programador?
 
TDC 2016 Floripa - Aprendendo Docker sem bruxaria
TDC 2016 Floripa - Aprendendo Docker sem bruxariaTDC 2016 Floripa - Aprendendo Docker sem bruxaria
TDC 2016 Floripa - Aprendendo Docker sem bruxaria
 
01-b-Ping
01-b-Ping01-b-Ping
01-b-Ping
 
TDC 2015 Floripa - Testes Automatizados de todos os tipos utilizando bibliote...
TDC 2015 Floripa - Testes Automatizados de todos os tipos utilizando bibliote...TDC 2015 Floripa - Testes Automatizados de todos os tipos utilizando bibliote...
TDC 2015 Floripa - Testes Automatizados de todos os tipos utilizando bibliote...
 
Selenium Workshop
Selenium Workshop Selenium Workshop
Selenium Workshop
 
TDC SP 2016 - EVDnC - Extreme Value-Driven Coaching - 4 sprints em 5 dias
TDC SP 2016 - EVDnC - Extreme Value-Driven Coaching - 4 sprints em 5 diasTDC SP 2016 - EVDnC - Extreme Value-Driven Coaching - 4 sprints em 5 dias
TDC SP 2016 - EVDnC - Extreme Value-Driven Coaching - 4 sprints em 5 dias
 

Similar to Writing Server in Python

Zeromq - Pycon India 2013
Zeromq - Pycon India 2013Zeromq - Pycon India 2013
Zeromq - Pycon India 2013
Srinivasan R
 
Comunicação Bluetooth Entre Python e PyS60
Comunicação Bluetooth Entre Python e PyS60Comunicação Bluetooth Entre Python e PyS60
Comunicação Bluetooth Entre Python e PyS60
Felipe Ronchi Brigido
 
Version1.0 StartHTML000000232 EndHTML000065057 StartFragment0000.docx
Version1.0 StartHTML000000232 EndHTML000065057 StartFragment0000.docxVersion1.0 StartHTML000000232 EndHTML000065057 StartFragment0000.docx
Version1.0 StartHTML000000232 EndHTML000065057 StartFragment0000.docx
tienboileau
 

Similar to Writing Server in Python (20)

Arp
ArpArp
Arp
 
Networking Core Concept
Networking Core ConceptNetworking Core Concept
Networking Core Concept
 
session6-Network Programming.pptx
session6-Network Programming.pptxsession6-Network Programming.pptx
session6-Network Programming.pptx
 
Assignment7.pdf
Assignment7.pdfAssignment7.pdf
Assignment7.pdf
 
Small pieces loosely joined
Small pieces loosely joinedSmall pieces loosely joined
Small pieces loosely joined
 
Introduction to asyncio
Introduction to asyncioIntroduction to asyncio
Introduction to asyncio
 
Zeromq - Pycon India 2013
Zeromq - Pycon India 2013Zeromq - Pycon India 2013
Zeromq - Pycon India 2013
 
Raspberry Pi à la GroovyFX
Raspberry Pi à la GroovyFXRaspberry Pi à la GroovyFX
Raspberry Pi à la GroovyFX
 
UDP.yash
UDP.yashUDP.yash
UDP.yash
 
Arduino and the real time web
Arduino and the real time webArduino and the real time web
Arduino and the real time web
 
Serverless stateful
Serverless statefulServerless stateful
Serverless stateful
 
clockDIGITAL.docx
clockDIGITAL.docxclockDIGITAL.docx
clockDIGITAL.docx
 
Comunicação Bluetooth Entre Python e PyS60
Comunicação Bluetooth Entre Python e PyS60Comunicação Bluetooth Entre Python e PyS60
Comunicação Bluetooth Entre Python e PyS60
 
tp socket en C.pdf
tp socket en C.pdftp socket en C.pdf
tp socket en C.pdf
 
[4] 아두이노와 인터넷
[4] 아두이노와 인터넷[4] 아두이노와 인터넷
[4] 아두이노와 인터넷
 
Interactive financial analytics with vix(cboe)
Interactive financial analytics with vix(cboe)Interactive financial analytics with vix(cboe)
Interactive financial analytics with vix(cboe)
 
Cdr stats-vo ip-analytics_solution_mongodb_meetup
Cdr stats-vo ip-analytics_solution_mongodb_meetupCdr stats-vo ip-analytics_solution_mongodb_meetup
Cdr stats-vo ip-analytics_solution_mongodb_meetup
 
CDR-Stats : VoIP Analytics Solution for Asterisk and FreeSWITCH with MongoDB
CDR-Stats : VoIP Analytics Solution for Asterisk and FreeSWITCH with MongoDBCDR-Stats : VoIP Analytics Solution for Asterisk and FreeSWITCH with MongoDB
CDR-Stats : VoIP Analytics Solution for Asterisk and FreeSWITCH with MongoDB
 
Version1.0 StartHTML000000232 EndHTML000065057 StartFragment0000.docx
Version1.0 StartHTML000000232 EndHTML000065057 StartFragment0000.docxVersion1.0 StartHTML000000232 EndHTML000065057 StartFragment0000.docx
Version1.0 StartHTML000000232 EndHTML000065057 StartFragment0000.docx
 
AWS IoTで家庭内IoTをやってみた【JAWS DAYS 2016】
AWS IoTで家庭内IoTをやってみた【JAWS DAYS 2016】AWS IoTで家庭内IoTをやってみた【JAWS DAYS 2016】
AWS IoTで家庭内IoTをやってみた【JAWS DAYS 2016】
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

Writing Server in Python

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 # client.py import socket s = socket.create_connection(('localhost', 8000)) while True: data = input('>> ') s.send(data.encode()) data = s.recv(1024) print(data) # server.py import socket s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('localhost', 8000)) s.listen(100) while True: client, __ = s.accept() data = client.recv(1024) while data: client.send(data) data = client.recv(1024) client.close()
  • 8. 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 # simple_http.py from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() self.wfile.write("Hello World".encode('utf8')) HTTPServer(('localhost', 8000), Handler).serve_forever()
  • 9. Thread Stats Avg Stdev Max +/- Stdev Latency 9.94s 21.79s 1.45m 83.49% Req/Sec 0.03 1.92 111.00 99.97% 703 requests in 1.67m, 70.71KB read Socket errors: connect 0, read 32, write 0, timeout 4604 Requests/sec: 7.03 Transfer/sec: 723.95B
  • 10.
  • 11.
  • 12.
  • 13. 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 # threaded_http.py from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from SocketServer import ThreadingMixIn class ThreadServer(ThreadingMixIn, HTTPServer): pass class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() self.wfile.write("Hello World".encode('utf8')) ThreadServer(('localhost', 8000), Handler).serve_forever()
  • 14. Thread Stats Avg Stdev Max +/- Stdev Latency 9.94s 21.79s 1.45m 83.49% Req/Sec 0.03 1.92 111.00 99.97% 703 requests in 1.67m, 70.71KB read Socket errors: connect 0, read 32, write 0, timeout 4604 Requests/sec: 7.03 Transfer/sec: 723.95B Thread Stats Avg Stdev Max +/- Stdev Latency 215.55ms 740.19ms 7.41s 92.21% Req/Sec 1.01 9.51 666.00 98.71% 10052 requests in 1.67m, 0.99MB read Socket errors: connect 0, read 0, write 0, timeout 344 Requests/sec: 100.50 Transfer/sec: 10.11KB
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21. import asyncio @asyncio.coroutine def handle_echo(reader, writer): data = yield from reader.read(100) while data: writer.write(data.decode()) yield from writer.drain() data = yield from reader.read(100) writer.close() try: loop = asyncio.get_event_loop() coro = asyncio.start_server(handle_echo, '127.0.0.1', 8000, loop=loop) server = loop.run_until_complete(coro) loop.run_forever() except: server.close() loop.run_until_complete(server.wait_closed()) loop.close() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
  • 22. import asyncio async def handle_echo(reader, writer): data = await reader.read(100) while data: writer.write(data) await writer.drain() data = await reader.read(100) writer.close() try: loop = asyncio.get_event_loop() coro = asyncio.start_server(handle_echo, '127.0.0.1', 8000, loop=loop) server = loop.run_until_complete(coro) loop.run_forever() except: server.close() loop.run_until_complete(server.wait_closed()) loop.close() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 3.5
  • 23. 1. Compatibilidade entre bibliotecas 2. Útil para aplicações IO bound ou com muitas conexões abertas mas sem processamento 3. Pode ser mais dificil de programar 4. Starvation