# echo_client.py
# coding=utf8
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('', 5500))
sock.send('hello socket world')
print sock.recv(1024)
上面简单的echo server 代码中有一点需要注意的是:server 端的 socket 设置了SO_REUSEADDR为1,目的是可以立
即使用处于TIME_WAIT状态的socket,那么TIME_WAIT又是什么意思呢?后面在讲解 tcp 状态变更图时再做详细介
绍。
UDP socket
UDP socket server 端代码在进行bind后,无需调用listen方法。
# udp_echo_server.py
# coding=utf8
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 设置 SO_REUSEADDR 后,可以立即使用 TIME_WAIT 状态的 socket
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', 5500))
# 没有调用 listen
if __name__ == '__main__':
while 1:
data, addr = sock.recvfrom(1024)
print('new client from %s:%s' % addr)
sock.sendto(data, addr)
# udp_echo_client.py
# coding=utf8
import socket
udp_server_addr = ('', 5500)
if __name__ == '__main__':
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
data_to_sent = 'hello udp socket'
try:
sent = sock.sendto(data_to_sent, udp_server_addr)
data, server = sock.recvfrom(1024)
print('receive data:[%s] from %s:%s' % ((data,) + server))
finally:
sock.close()