import socket
import threading

# 创建套接字          使用ipv4         使用tcp协议
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
sock.connect(('localhost', 5550))
# 发送验证信息
sock.send(b'1')
# 接收 解码 服务器发回的信息
print(sock.recv(1024).decode())
# 接收用户输入
nickName = input('input your nickname: ')
# 把用户输入的东西发送到服务器
sock.send(nickName.encode())

# 发送信息线程回调函数
def sendThreadFunc():
    while True:
        try:
            myword = input()
            sock.send(myword.encode())
            # print(sock.recv(1024).decode())
        except ConnectionAbortedError:
            print('Server closed this connection!')
        except ConnectionResetError:
            print('Server is closed!')

# 接收信息线程回调函数
def recvThreadFunc():
    while True:
        try:
            otherword = sock.recv(1024)
            if otherword:
                print(otherword.decode())
            else:
                pass
        except ConnectionAbortedError:
            print('Server closed this connection!')

        except ConnectionResetError:
            print('Server is closed!')

#  创建了 两个线程 一个发送一个接收
th1 = threading.Thread(target=sendThreadFunc)
th2 = threading.Thread(target=recvThreadFunc)
threads = [th1, th2]

# 两个都设置 进程守护
for t in threads:
    t.setDaemon(True)
    t.start()
# 主线程等待子线程结束
t.join((timeout=None)