User Tools

Site Tools


rx3:index

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Last revisionBoth sides next revision
rx3:index [2018/04/06 08:01] orelrx3:index [2021/02/23 11:38] – [Client HTTP/GET (TCP)] orel
Line 1: Line 1:
 ====== Réseau L2 Info : Socket en Python 3 ====== ====== Réseau L2 Info : Socket en Python 3 ======
 +
 +
 +Un peu de documentation :
 +
 +  * https://docs.python.org/3/howto/sockets.html
 +  * https://docs.python.org/3/library/socket.html
 +  * https://docs.python.org/3/library/select.html
 +  * https://docs.python.org/3/library/threading.html
 +  * https://docs.python.org/3/library/stdtypes.html#str 
 +
  
 ==== Tips en Python ==== ==== Tips en Python ====
Line 156: Line 166:
 <code python> <code python>
 #!/usr/bin/python3 #!/usr/bin/python3
-import sys 
 import socket import socket
- 
-HOST = 'www.labri.fr'      
-PORT = 80                  
 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-s.connect((HOSTPORT)) +s.connect(("www.perdu.com"80)) 
-s.sendall(b'GET /\r\n\r\n')+s.sendall(b'GET / HTTP/1.1\r\nHost: www.perdu.com\r\nConnection: close\r\n\r\n')
 data = s.recv(1024) data = s.recv(1024)
 s.close() s.close()
Line 229: Line 235:
     sclient.close()     sclient.close()
 </code>             </code>            
 +
 +==== Serveur TCP (version multithread) ====
 +
 +<code python>
 +#!/usr/bin/python3
 +import socket
 +import threading
 +
 +
 +def handle(addr, sclient):
 +    print('Connected by', addr)
 +    while True:
 +        data = sclient.recv(1500)
 +        if data == b'' or data == b'\n':
 +            break
 +        print(data)
 +        sclient.sendall(data)
 +    print('Disconnected by', addr)
 +    sclient.close()
 +
 +
 +HOST = ''
 +PORT = 7777
 +s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 +s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 +s.bind((HOST, PORT))
 +s.listen(0)
 +while True:
 +    sclient, addr = s.accept()
 +    t = threading.Thread(None, handle, None, (addr, sclient))
 +    t.start()
 +</code>
  
 ==== Serveur Echo TCP (version select) ==== ==== Serveur Echo TCP (version select) ====
Line 271: Line 309:
 s.close() s.close()
 </code> </code>
-==== Documentation ==== 
- 
-  * https://docs.python.org/3/library/socket.html 
-  * https://docs.python.org/3/library/select.html 
-  * https://docs.python.org/3/library/threading.html 
-  * https://docs.python.org/3/library/stdtypes.html#str 
- 
- 
  
  
rx3/index.txt · Last modified: 2024/03/18 15:06 by 127.0.0.1