Writing Server in Python

Writing Server in Python
Writing Server in Python
Writing Server in Python
Writing Server in Python
Writing Server in Python
Writing Server in Python
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
Writing Server in Python
Writing Server in Python
Writing Server in Python
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
Writing Server in Python
Writing Server in Python
Writing Server in Python
Writing Server in Python
Writing Server in Python
Writing Server in Python
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
1 of 24

Recommended

The Ring programming language version 1.10 book - Part 61 of 212 by
The Ring programming language version 1.10 book - Part 61 of 212The Ring programming language version 1.10 book - Part 61 of 212
The Ring programming language version 1.10 book - Part 61 of 212Mahmoud Samir Fayed
8 views10 slides
The Ring programming language version 1.5.4 book - Part 50 of 185 by
The Ring programming language version 1.5.4 book - Part 50 of 185The Ring programming language version 1.5.4 book - Part 50 of 185
The Ring programming language version 1.5.4 book - Part 50 of 185Mahmoud Samir Fayed
8 views10 slides
The Ring programming language version 1.5.3 book - Part 50 of 184 by
The Ring programming language version 1.5.3 book - Part 50 of 184The Ring programming language version 1.5.3 book - Part 50 of 184
The Ring programming language version 1.5.3 book - Part 50 of 184Mahmoud Samir Fayed
18 views10 slides
The Ring programming language version 1.6 book - Part 69 of 189 by
The Ring programming language version 1.6 book - Part 69 of 189The Ring programming language version 1.6 book - Part 69 of 189
The Ring programming language version 1.6 book - Part 69 of 189Mahmoud Samir Fayed
10 views10 slides
The Ring programming language version 1.3 book - Part 40 of 88 by
The Ring programming language version 1.3 book - Part 40 of 88The Ring programming language version 1.3 book - Part 40 of 88
The Ring programming language version 1.3 book - Part 40 of 88Mahmoud Samir Fayed
53 views10 slides
The Ring programming language version 1.5.1 book - Part 63 of 180 by
The Ring programming language version 1.5.1 book - Part 63 of 180The Ring programming language version 1.5.1 book - Part 63 of 180
The Ring programming language version 1.5.1 book - Part 63 of 180Mahmoud Samir Fayed
26 views10 slides

More Related Content

What's hot

The Ring programming language version 1.5.2 book - Part 49 of 181 by
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 181Mahmoud Samir Fayed
9 views10 slides
Асинхронность и многопоточность в Яндекс.Такси — Дмитрий Курилов by
Асинхронность и многопоточность в Яндекс.Такси — Дмитрий КуриловАсинхронность и многопоточность в Яндекс.Такси — Дмитрий Курилов
Асинхронность и многопоточность в Яндекс.Такси — Дмитрий КуриловYandex
887 views29 slides
A promise is a Promise by
A promise is a PromiseA promise is a Promise
A promise is a PromiseMateusz Bryła
155 views68 slides
Programa donde suma las filass de las dos columna y ordena el resultado de l... by
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
596 views1 slide
The Ring programming language version 1.5.1 book - Part 48 of 180 by
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 180Mahmoud Samir Fayed
24 views10 slides
The Ring programming language version 1.5.1 book - Part 60 of 180 by
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 180Mahmoud Samir Fayed
21 views10 slides

What's hot(20)

The Ring programming language version 1.5.2 book - Part 49 of 181 by Mahmoud Samir Fayed
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
Асинхронность и многопоточность в Яндекс.Такси — Дмитрий Курилов by Yandex
Асинхронность и многопоточность в Яндекс.Такси — Дмитрий КуриловАсинхронность и многопоточность в Яндекс.Такси — Дмитрий Курилов
Асинхронность и многопоточность в Яндекс.Такси — Дмитрий Курилов
Yandex887 views
The Ring programming language version 1.5.1 book - Part 48 of 180 by Mahmoud Samir Fayed
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 by Mahmoud Samir Fayed
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
The Ring programming language version 1.5.4 book - Part 53 of 185 by Mahmoud Samir Fayed
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 by Mahmoud Samir Fayed
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 by Mahmoud Samir Fayed
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 by Mahmoud Samir Fayed
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 by Mahmoud Samir Fayed
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 by Mahmoud Samir Fayed
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 by Mahmoud Samir Fayed
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 by Mahmoud Samir Fayed
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 by ogdc
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
ogdc2.8K views
Ogdc 2013 lets remake the wheel by Son Aris
Ogdc 2013 lets remake the wheelOgdc 2013 lets remake the wheel
Ogdc 2013 lets remake the wheel
Son Aris655 views
The Ring programming language version 1.3 book - Part 50 of 88 by Mahmoud Samir Fayed
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 by Mahmoud Samir Fayed
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 by Mahmoud Samir Fayed
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

Cloud computing by
Cloud computingCloud computing
Cloud computingEdson Yanaga
431 views16 slides
Scrum Gathering Rio 2014 - Melhorando sua Estratégia de Testes Automatizados by
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 AutomatizadosStefan Teixeira
1.5K views44 slides
O que é ser um bom programador? by
O que é ser um bom programador?O que é ser um bom programador?
O que é ser um bom programador?Lucas Boeing Scarduelli
1.8K views85 slides
TDC 2016 Floripa - Aprendendo Docker sem bruxaria by
TDC 2016 Floripa - Aprendendo Docker sem bruxariaTDC 2016 Floripa - Aprendendo Docker sem bruxaria
TDC 2016 Floripa - Aprendendo Docker sem bruxariaStefan Teixeira
1.2K views25 slides
01-b-Ping by
01-b-Ping01-b-Ping
01-b-PingMarcio Marchini
1.1K views45 slides
TDC 2015 Floripa - Testes Automatizados de todos os tipos utilizando bibliote... by
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...Stefan Teixeira
1.5K views34 slides

Viewers also liked(8)

Scrum Gathering Rio 2014 - Melhorando sua Estratégia de Testes Automatizados by Stefan Teixeira
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
Stefan Teixeira1.5K views
TDC 2016 Floripa - Aprendendo Docker sem bruxaria by Stefan Teixeira
TDC 2016 Floripa - Aprendendo Docker sem bruxariaTDC 2016 Floripa - Aprendendo Docker sem bruxaria
TDC 2016 Floripa - Aprendendo Docker sem bruxaria
Stefan Teixeira1.2K views
TDC 2015 Floripa - Testes Automatizados de todos os tipos utilizando bibliote... by Stefan Teixeira
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...
Stefan Teixeira1.5K views
Selenium Workshop by Thoughtworks
Selenium Workshop Selenium Workshop
Selenium Workshop
Thoughtworks5.4K views
TDC SP 2016 - EVDnC - Extreme Value-Driven Coaching - 4 sprints em 5 dias by Luiz Rodrigues
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
Luiz Rodrigues7.9K views

Similar to Writing Server in Python

from socket import - serverPort-12000 address - ('localhost'- serverPo.pdf by
from socket import - serverPort-12000 address - ('localhost'- serverPo.pdffrom socket import - serverPort-12000 address - ('localhost'- serverPo.pdf
from socket import - serverPort-12000 address - ('localhost'- serverPo.pdfgargtex
15 views2 slides
Arp by
ArpArp
ArpEbsil Sherly
508 views8 slides
Networking Core Concept by
Networking Core ConceptNetworking Core Concept
Networking Core ConceptRays Technologies
24 views15 slides
session6-Network Programming.pptx by
session6-Network Programming.pptxsession6-Network Programming.pptx
session6-Network Programming.pptxSrinivasanG52
6 views12 slides
Assignment7.pdf by
Assignment7.pdfAssignment7.pdf
Assignment7.pdfdash41
37 views6 slides
Small pieces loosely joined by
Small pieces loosely joinedSmall pieces loosely joined
Small pieces loosely joinedennui2342
631 views41 slides

Similar to Writing Server in Python(20)

from socket import - serverPort-12000 address - ('localhost'- serverPo.pdf by gargtex
from socket import - serverPort-12000 address - ('localhost'- serverPo.pdffrom socket import - serverPort-12000 address - ('localhost'- serverPo.pdf
from socket import - serverPort-12000 address - ('localhost'- serverPo.pdf
gargtex15 views
session6-Network Programming.pptx by SrinivasanG52
session6-Network Programming.pptxsession6-Network Programming.pptx
session6-Network Programming.pptx
SrinivasanG526 views
Assignment7.pdf by dash41
Assignment7.pdfAssignment7.pdf
Assignment7.pdf
dash4137 views
Small pieces loosely joined by ennui2342
Small pieces loosely joinedSmall pieces loosely joined
Small pieces loosely joined
ennui2342631 views
Zeromq - Pycon India 2013 by Srinivasan R
Zeromq - Pycon India 2013Zeromq - Pycon India 2013
Zeromq - Pycon India 2013
Srinivasan R5.1K views
Raspberry Pi à la GroovyFX by Stephen Chin
Raspberry Pi à la GroovyFXRaspberry Pi à la GroovyFX
Raspberry Pi à la GroovyFX
Stephen Chin4.5K views
Please study the Python code shown below- The questions are based on t.docx by PeterlqELawrenceb
Please study the Python code shown below- The questions are based on t.docxPlease study the Python code shown below- The questions are based on t.docx
Please study the Python code shown below- The questions are based on t.docx
ATM Socket Program in Python EDITCode two separate programs a cl.pdf by FashionColZone
ATM Socket Program in Python EDITCode two separate programs a cl.pdfATM Socket Program in Python EDITCode two separate programs a cl.pdf
ATM Socket Program in Python EDITCode two separate programs a cl.pdf
FashionColZone3 views
Arduino and the real time web by Andrew Fisher
Arduino and the real time webArduino and the real time web
Arduino and the real time web
Andrew Fisher24.6K views
[4] 아두이노와 인터넷 by Chiwon Song
[4] 아두이노와 인터넷[4] 아두이노와 인터넷
[4] 아두이노와 인터넷
Chiwon Song907 views
Interactive financial analytics with vix(cboe) by Aiden Wu, FRM
Interactive financial analytics with vix(cboe)Interactive financial analytics with vix(cboe)
Interactive financial analytics with vix(cboe)
Aiden Wu, FRM48 views
Cdr stats-vo ip-analytics_solution_mongodb_meetup by christkv
Cdr stats-vo ip-analytics_solution_mongodb_meetupCdr stats-vo ip-analytics_solution_mongodb_meetup
Cdr stats-vo ip-analytics_solution_mongodb_meetup
christkv1.1K views

Recently uploaded

"Node.js Development in 2024: trends and tools", Nikita Galkin by
"Node.js Development in 2024: trends and tools", Nikita Galkin "Node.js Development in 2024: trends and tools", Nikita Galkin
"Node.js Development in 2024: trends and tools", Nikita Galkin Fwdays
17 views38 slides
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas... by
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...Bernd Ruecker
48 views69 slides
Igniting Next Level Productivity with AI-Infused Data Integration Workflows by
Igniting Next Level Productivity with AI-Infused Data Integration Workflows Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows Safe Software
317 views86 slides
PharoJS - Zürich Smalltalk Group Meetup November 2023 by
PharoJS - Zürich Smalltalk Group Meetup November 2023PharoJS - Zürich Smalltalk Group Meetup November 2023
PharoJS - Zürich Smalltalk Group Meetup November 2023Noury Bouraqadi
139 views17 slides
GDSC CTU First Meeting Party by
GDSC CTU First Meeting PartyGDSC CTU First Meeting Party
GDSC CTU First Meeting PartyNational Yang Ming Chiao Tung University
11 views25 slides
Piloting & Scaling Successfully With Microsoft Viva by
Piloting & Scaling Successfully With Microsoft VivaPiloting & Scaling Successfully With Microsoft Viva
Piloting & Scaling Successfully With Microsoft VivaRichard Harbridge
13 views160 slides

Recently uploaded(20)

"Node.js Development in 2024: trends and tools", Nikita Galkin by Fwdays
"Node.js Development in 2024: trends and tools", Nikita Galkin "Node.js Development in 2024: trends and tools", Nikita Galkin
"Node.js Development in 2024: trends and tools", Nikita Galkin
Fwdays17 views
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas... by Bernd Ruecker
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
Bernd Ruecker48 views
Igniting Next Level Productivity with AI-Infused Data Integration Workflows by Safe Software
Igniting Next Level Productivity with AI-Infused Data Integration Workflows Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Safe Software317 views
PharoJS - Zürich Smalltalk Group Meetup November 2023 by Noury Bouraqadi
PharoJS - Zürich Smalltalk Group Meetup November 2023PharoJS - Zürich Smalltalk Group Meetup November 2023
PharoJS - Zürich Smalltalk Group Meetup November 2023
Noury Bouraqadi139 views
Piloting & Scaling Successfully With Microsoft Viva by Richard Harbridge
Piloting & Scaling Successfully With Microsoft VivaPiloting & Scaling Successfully With Microsoft Viva
Piloting & Scaling Successfully With Microsoft Viva
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors by sugiuralab
TouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective SensorsTouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective Sensors
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors
sugiuralab23 views
STPI OctaNE CoE Brochure.pdf by madhurjyapb
STPI OctaNE CoE Brochure.pdfSTPI OctaNE CoE Brochure.pdf
STPI OctaNE CoE Brochure.pdf
madhurjyapb14 views
Webinar : Desperately Seeking Transformation - Part 2: Insights from leading... by The Digital Insurer
Webinar : Desperately Seeking Transformation - Part 2:  Insights from leading...Webinar : Desperately Seeking Transformation - Part 2:  Insights from leading...
Webinar : Desperately Seeking Transformation - Part 2: Insights from leading...
Unit 1_Lecture 2_Physical Design of IoT.pdf by StephenTec
Unit 1_Lecture 2_Physical Design of IoT.pdfUnit 1_Lecture 2_Physical Design of IoT.pdf
Unit 1_Lecture 2_Physical Design of IoT.pdf
StephenTec15 views

Writing Server in Python

  • 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
  • 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
  • 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