TCP客户端模型:
import socket # 创建tcp套接字对象 sockfd = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 绑定地址 ip: "localhost" "127.0.0.1" "0.0.0.0" "192.168.31.196" sockfd.bind(("127.0.0.1",8888)) # 设置监听套接字 sockfd.listen(3) # 处理客户端链接 while True: print("Waiting for connect..") connfd,addr = sockfd.accept() print("Connect from",addr) # 收发消息 (网络传输数据用字节串) while True: data = connfd.recv(1024) if not data: break # 收到b"##"则退出 # if data == b"##": # break print("Recv:",data.decode()) n = connfd.send(b'Thanks') print("Send %d bytes"%n) connfd.close() # 关闭套接字 sockfd.close()
TCP服务端模型:
from socket import * # 服务器地址 server_addr = ("127.0.0.1",8888) # 创建tcp套接字 sockfd = socket() # 默认值就是tcp # 连接服务器 sockfd.connect(server_addr) # 发送接收消息 while True: data = input(">>") if not data: break sockfd.send(data.encode()) # 输入##表示退出 # if data == '##': # break data = sockfd.recv(1024) print("From server:",data.decode()) sockfd.close()
来源:CSDN
作者:Uranus_user
链接:https://blog.csdn.net/Uranus_user/article/details/104762583