写过Socket网络编程的代码,大致都知道一个tcp服务器的主要步骤:socket–>bind–>listen–>accept–>recv/send–>close, tcp客户端的主要 步骤:socket–>connect–>recv/send–>close。有上述的了解的话,会觉得Python中的socket编程也是类似的。
以一个echo服务为例子,进行说明:
1)首先是服务端的代码:
# This is a echo server.
import socket
import sys
try:
#1. create socket
serv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print("socket failed")
sys.exit(-1)
print("socket success")
# serv_addr = ('127.0.0.1', 8080)
host = ''
port = 8000
#2. bind to 8000 port and listen
serv_sock.bind((host, port))
serv_sock.listen(5)
while True:
#3. accept connection from client
client_sock, client_addr = serv_sock.accept()
print("connected by ", client_addr)
while True:
buf = client_sock.recv(10240)
if not buf:
print("Exit", client_addr)
client_sock.close()
break
else:
print("recv from client: ", buf)
client_sock.send(buf)
2)echo客户端代码:
# This is a echo client.
import socket
import sys
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print('socket failed!')
sys.exit(-1)
print("socket success")
# serv_addr = ('127.0.0.1', 8080)
host = '127.0.0.1'
port = 8000
try:
sock.connect((host, port))
except socket.error:
print("connect %s failed" % host)
sys.exit(-1)
while True:
try:
#message = "hello"
message = input(">>")
if not message:
break
else:
sock.sendall(message.encode('utf8'))
reply = sock.recv(10240)
print('reply: %s' % reply.decode('utf8'))
except EOFError:
print("EOF\n")
break
print("Exit...")
#sock.shutdown(socket.SHUT_RDWR)
sock.close()
上述就是一个简单的echo服务,简单的展示了socket模块中的套接字编程的相关方法。
在实际的网络开发中,主要的模型有:多进程,多线程,事件驱动select/epoll,异步非阻塞。这些会在后面的文章中分别进行说明。