'''
Created on 2019-10-16
Client_SOCKET:多线程客户端信息监听收发
@author: heidu004
'''
#!/usr/bin/python3
# -*-coding:utf-8 -*-
import threading
from socket import socket, AF_INET, SOCK_STREAM
class ClientSocket:
def __init__(self,ADDR,BUFSIZ,exitFlag):
self.ADDR =ADDR#IP地址及端口
self.BUFSIZ=BUFSIZ#缓冲
self.tcp_client_sock = socket(AF_INET, SOCK_STREAM)
self.exitFlag=exitFlag
def start(self):
try:
self.tcp_client_sock.connect(self.ADDR)
print("服务器连接成功")
except Exception:
print("服务器连接失败,检查IP地址是否正常")
self.exitFlag = False
def clientdata(self):#接收数据
while self.exitFlag:
try:
data =self.tcp_client_sock.recv(self.BUFSIZ)
if not data:
break
print(data.decode())
except Exception:
self.exitFlag=False
break
def clientsend(self):#发送数据
while self.exitFlag:
data=input(">>")
if data=="EXIT":
break
try:
self.tcp_client_sock.send(data.encode('utf-8'))
except Exception:
self.exitFlag=False
break
self.tcp_client_sock.close()
class ClientThread(threading.Thread):#Client接受消息线程
def __init__(self,cFlag):
threading.Thread.__init__(self)
self.cFlag=cFlag
def run(self):#监听消息
#threadLock.acquire()#锁定
if self.cFlag=='input':
c_s.clientsend()
elif self.cFlag=='data':
c_s.clientdata()
#threadLock.release()#释放
def main():
#threadLock =threading.Lock()#创建锁
threads = []#Client线程组
#创建新线程
cThread1 =ClientThread('input')
cThread2 =ClientThread('data')
#开启线程
cThread1.start()
cThread2.start()
#添加线程列表
threads.append(cThread1)#添加线程组
threads.append(cThread2)#添加线程组
#等待所有线程程序完成
for t in threads:
t.join()
print("退出主程序")
if __name__== '__main__':
print("--------------------------")
print('(o゜▽゜)o☆[BINGO!],CLIENT客户端以启动')
print('START:启动 EXIT:关闭')
data=input(">>")
if data =="START":
ips=input("IP>>")
port=input("POTR>>")
ADDR = (ips, int(port))#IP地址及端口
#ADDR = ('localhost', 1234)#IP地址及端口
BUFSIZ=1024#缓冲
exitFlag=True
c_s=ClientSocket(ADDR,BUFSIZ,exitFlag)#创建连接IP初始化缓冲
c_s.start()#连接服务器
main()
elif data =="EXIT":
exit()