1、客户端
from socket import * def main(): # 创建套接字 tcp_socket = socket(AF_INET,SOCK_STREAM) # 链接服务端 ip = input('请输入链接ip:') port = int(input('请输入链接port:')) dest_addr = (ip,port) tcp_socket.connect(dest_addr) # 发送内容 while True: sent_date = input('请输入发送内容:') date = tcp_socket.send(sent_date.encode('utf-8')) # 关闭套接字 tcp_socket.close() if __name__ == '__main__': main()
2、tcp_服务端
from socket import * def main(): # 创建套接字 tcp_service = socket(AF_INET,SOCK_STREAM) # 绑定端口地址 tcp_service.bind(('',5060)) # listen是套接字变被动连接 tcp_service.listen(128) # accept 等待客户段接入 client_socket,client_addr = tcp_service.accept() # 接收内容 while True: rec_date = client_socket.recv(1024) print('接收到的内容:',rec_date.decode('utf-8')) # 关闭套接字 client_socket.close() if __name__ == '__main__': main()