1.服务端
import socket
import threading
import sys
def socket_service():
try:
# 创建socket对象,使用ipv4协议 TCP通信链接
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 防止socket server重启后端口被占用
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 设置ip地址和端口
s.bind(('127.0.0.1', 8808))
# 最大等待数
s.listen(5)
print('Waiting connection...\n')
while True:
# 等待客户端链接
conn, addr = s.accept()
# 为客户端起个线程
t = threading.Thread(target=deal_data, args=(conn, addr))
# 设置守护线程
t.setDaemon(True)
# 启动线程
t.start()
except socket.error as msg:
print(msg)
sys.exit(1)
finally:
s.close()
def deal_data(conn, addr):
try:
print('{0}与您建立了链接\n'.format(addr))