TCP server
import socket
s= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('127.0.0.1',4567))
s.listen(5) #5:連接的最大數(shù)量
sock,addr = s.accept()
sock.send(b'Welcome!')
data = sock.recv(1024)
sock.close()
TCP client
importsocket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('127.0.0.1',4567))
s.recv(1024).decode('utf-8')
s.send('abcd')
s.close()
UDP server
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(('127.0.0.1',9999))
data,addr = s.recvfrom(1024)
s.sendto(b'Hello, %s!'% data,addr)
UDP client
importsocket
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.sendto('VanCare',('127.0.0.1',9999))
s.recv(1024).decode('utf-8')
s.close()