python网络编程
- 链接
socket
- server
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:server.py
import socket # 导入 socket 模块
s = socket.socket() # 创建 socket 对象
host = socket.gethostname() # 获取本地主机名
port = 12345 # 设置端口
s.bind((host, port)) # 绑定端口
s.listen(5) # 等待客户端连接
while True:
c, addr = s.accept() # 建立客户端连接。
print('连接地址:', addr)
c.send(b'hello world')
c.close() # 关闭连接
- client
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:client.py
import socket # 导入 socket 模块
s = socket.socket() # 创建 socket 对象
host = socket.gethostname() # 获取本地主机名
port = 12345 # 设置端口号
s.connect((host, port))
print(s.recv(1024))
s.close()
- 服务器命令窗口:
➜ python-socket python3 server.py
连接地址: ('10.111.152.120', 60878)
- 客户端命令窗口
➜ python-socket python3 client.py
b'hello world'