Сокеты (простые примеры)
Простые примеры по работе с UDP и TCP-сокетами для Python. Возможны незначительные вариации синтаксиса между 2.7 и 3 версией python. Simple sockets python
UDP - half-duplex datagram Server ============================================= from socket import *
u = socket(AF_INET, SOCK_DGRAM) u.bind(("0.0.0.0",1234)) // ip-port tuple to bind server
while 1:
message,sender= u.recvfrom(1024) print 'Client' + str(sender) + ' said: ' + message if message == : break
Client ============================================= from socket import *
u = socket(AF_INET, SOCK_DGRAM) u.sendto("Hello world!", ("1.2.3.4",1234)) // ip-port tuple of server
TCP - full-duplex stream Server ============================================= from socket import *
t = socket(AF_INET, SOCK_STREAM) t.bind(("0.0.0.0",1234)) t.listen() c = t.accept() c c[0].recv(200)
'jellojellojello'
c[0].send(b"Hi")
Client ==============================================
from socket import *
t = socket(AF_INET, SOCK_STREAM)
t.connect(("1.2.3.4",1234))
socket.error: [Errno 111] Connection refused
t.send(b"jello") t.recv(10)
while 1:
t.send(b"jello")
x.close()