1. TCP数据通讯
服务端:文章来源:https://www.toymoban.com/news/detail-623188.html
import socket
host = '192.168.33.1' # 服务端IP地址
prot = 8080 # 设置端口号(可任意)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建套接字
server_socket.bind((host, prot)) # 将地址(主机名、端口号)绑定到套接字上
server_socket.listen(5) # 设置并启动TCP监听器,参数5是在连接被转接或拒绝之前,传入连接请求的最大数连接队列最大值。
print("等待客户端连接...")
client_socket, address = server_socket.accept() # 被动接受TCP客户端连接,持续等待直到连接到达(阻塞等待)。
print("连接来自: %s:%s" % address) # 显示请求连接的客户端的地址
while True:
data = client_socket.recv(1024) # 接受客户端发来的数据
if not data:
print("客户端%s:%s断开连接" % address)
break
print("接收到来自%s:%s的消息:" % address)
print(data.decode('utf-8'))
server_socket.close() # 退出服务器端
客户端:文章来源地址https://www.toymoban.com/news/detail-623188.html
import socket
import time
host = '192.168.33.1' # 服务端IP地址
prot = 8080 # 服务端端口号
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建套接字
# client_socket.bind((host, 9990)) # 客户端配置自己从哪一个端口访问服务端,9990可任意
client_socket.connect((host, prot)) # 客户端向服务端发起连接
data = client_socket.recv(1024) # 接受数据
print(data.decode(('utf-8'))) #显示数据
while True :
client_socket.send(b'Connection successful.') # 发送消息
time.sleep(2) # 等待2秒
client_socket.close() # 退出客户器端
2. socket 客户端断开,服务端依然保持监听
服务端采用try...except ..形式,代码如下:
import socket
host = '192.168.33.1' # 服务端IP地址
prot = 8080 # 设置端口号(可任意)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建套接字
server_socket.bind((host, prot)) # 将地址(主机名、端口号)绑定到套接字上
server_socket.listen(5) # 设置并启动TCP监听器,参数5是在连接被转接或拒绝之前,传入连接请求的最大数连接队列最大值。
print("等待客户端连接...")
while True:
try:
client_socket, address = server_socket.accept() # 被动接受TCP客户端连接,持续等待直到连接到达(阻塞等待)。
print("连接来自: %s:%s" % address) # 显示请求连接的客户端的地址
while True:
data = client_socket.recv(1024) # 接受客户端发来的数据
if not data:
print("客户端%s:%s断开连接" % address)
break
print("接收到来自%s:%s的消息:" % address)
print(data.decode('utf-8'))
except ConnectionResetError:
print("客户端 %s:%s异常断开连接" % address)
continue
except KeyboardInterrupt:
print("服务器关闭")
break
server_socket.close() # 退出服务器端
3. 用threading 模块Thread 类,加入多线程,修改服务端如下:
import socket
import threading
import time
host = '192.168.33.1'
prot = 8080
def tcplink():
num = 1
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, prot))
server_socket.listen(5)
print("等待客户端连接...")
while True:
try:
client_socket, address = server_socket.accept()
print("连接来自: %s:%s" % address)
client_socket.send(b'welcome')
time.sleep(2)
while True:
data = client_socket.recv(1024)
if not data:
print("客户端%s:%s断开连接" % address)
break
# client_socket.send(data)
print("接收到来自%s:%s的消息:" % address)
print(data.decode('utf-8'))
except ConnectionResetError:
print("客户端 %s:%s异常断开连接" % address)
continue
except KeyboardInterrupt:
print("服务器关闭")
break
server_socket.close()
print("客户端%s:%s断开连接" % address)
if __name__ == '__main__':
t = threading.Thread(target=tcplink)
t.start()
4. 一个服务端配备多个客户端,修改服务端如下:
import socket
import threading
import time
host = '192.168.33.1'
prot = 8080
def tcplink_recv(client_socket,address):
while True:
try:
data = client_socket.recv(1024)
if not data:
print("客户端%s:%s断开连接" % address)
break
# client_socket.send(data)
print("接收到来自%s:%s的消息:" % address)
print(data.decode('utf-8'))
except :
print("客户端 %s:%s异常断开连接" % address)
break
def tcplink():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, prot))
server_socket.listen(5)
print("等待客户端连接...")
while True:
try:
client_socket, address = server_socket.accept()
print("连接来自: %s:%s" % address)
client_socket.send(b'welcome')
t = threading.Thread(target=tcplink_recv,args=(client_socket, address))
t.start()
time.sleep(2)
except ConnectionResetError:
print("客户端 %s:%s异常断开连接" % address)
continue
except KeyboardInterrupt:
print("服务器关闭")
break
server_socket.close()
print("客户端%s:%s断开连接" % address)
if __name__ == '__main__':
t = threading.Thread(target=tcplink)
t.start()
5. 客户端发送数组或者字典时,需要对数据转码,采用json模块,修改客户端代码如下:
import socket
import time
import json
host = '192.168.33.1' # 服务端IP地址
prot = 8080 # 服务端端口号
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# client_socket.bind((host, 9990))
client_socket.connect((host, prot))
data = client_socket.recv(1024)
print(data.decode(('utf-8')))
list = [1,1,1]
# list = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
while True :
list_json = json.dumps(list) # 转码
client_socket.send(bytes(list_json.encode('utf-8'))) # socket发送的数据类型是字节
time.sleep(2)
client_socket.close()
到了这里,关于python实现TCP数据通讯,socket 客户端断开依然保持监听,多线程。的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!