最近看书浏览到 Socket 网络模块,想尝试用 Python3 写一下 Socket 的例子,结果遇到一点坑,下面是调整后跑通的例子,方便以后查看。
两个类:
- 服务端
- 客户端
运行过程:
- 首先启动服务端,监听请求;
- 然后通过客户端去发出请求;
- 接下来观察输出;
服务端源代码SocketServer.py
:
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print('Got connection from {}'.format(addr))
print('Received message == {}'.format(c.recv(1024).decode('utf-8')))
c.send(b'this come from server')
c.close()
客户端源代码SocketClient.py
:
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.connect((host, port))
print('Try to send connection from {}'.format(host))
s.sendall(b"this come from client")
print(s.recv(1024).decode('utf-8'))
服务端输出如下:
Got connection from ('x.x.x.x', x)
Received message == this come from client
客户端输出如下:
Try to send connection from x.local
this come from server
Process finished with exit code 0