import socket
import threading
class TcpClass():
def __init__(self,ip,port):
self.tcpSocket = socket.socket()
self.ip = ip
self.port = port
self.run = False
self.connect()
if self.run:
self.thread1 = threading.Thread(target=self.receiveData)
self.thread2 = threading.Thread(target=self.sendData)
self.thread1.start()
self.thread2.start()
self.thread1.join()
self.thread2.join()
self.close()
def connect(self):
try:
self.tcpSocket.connect((self.ip,self.port))
self.run = True
print('服务器已连接')
except:
print('服务器连接失败')
self.close()
def close(self):
self.tcpSocket.close()
print('断开服务器')
def sendData(self):
print("sendData")
while self.run:
send_data = input()
if send_data:
self.tcpSocket.send(send_data.encode("gbk"))
print('发送服务器数据:%s' % send_data)
if send_data == "断开连接":
print("发送数据线程已结束")
self.run = False
def receiveData(self):
print("receiveData")
while self.run:
receive_data = self.tcpSocket.recv(1024).decode("gbk")
print('接收服务器数据:%s' % receive_data)
if receive_data == "断开连接" or receive_data == "":
print("接收数据线程已结束")
self.run = False
a = TcpClass('10.1.211.76',7788)
input("输入任意字符结束程序!")
02-06
384
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-25
6484
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
11-09
1651
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)