本文接自上篇文档,展示客户端篇的代码,前一篇服务器的默认端口是8888,IP地址可自行获取本地IP
# -*- coding: utf-8 -*-# @Time : /6/19 16:56# @Author : 飞鸟凌# @File : tcp_socket_09客户端通信器.pyimport threadingimport socketmy_name = "客户端"goal_name = "服务器"encoding = "utf-8"sever_ip = ""sever_port = Noneloop = 0def send_my(tcp_socket):while True:send_data = input(my_name + ":|")print()if send_data == "exit":breaktcp_socket.send(send_data.encode(encoding))def rev_my(new_socket):global loopwhile True:try:rev_data = new_socket.recv(1024)except ConnectionError as e:print("\n服务器已断开连接")loop = 1breakprint("\n")print("%s:|%s".rjust(37, " ") % (rev_data.decode(encoding), goal_name))print(my_name + ":|", end="")def menu():global sever_ip, sever_portsever_ip = input("请输入服务器的ip地址:")sever_port = int(input("请输入服务器的端口:"))print("udp_socket客户端通信器".center(50, " "))print("=" * 50)def main():# 1.菜单提示menu()# 2.创建套接字tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 3.链接服务器tcp_socket.connect((sever_ip, sever_port))# while True:# 6.创建子线程发送数据send_t = threading.Thread(target=send_my, args=(tcp_socket,))# 7.创建子线程接收数据rev_t = threading.Thread(target=rev_my, args=(tcp_socket,))# 8.线程开始rev_t.start()send_t.start()# 9.关闭局部套接字global loopwhile loop == 0:passloop = 0tcp_socket.close()if __name__ == '__main__':main()