Benjamin

静以修身,俭以养德,非澹薄无以明志,非宁静无以致远。
随笔 - 397, 文章 - 0, 评论 - 196, 引用 - 0
数据加载中……

python tcp client

import threading
import socket
# ------------------------Client------------------------
class Client:
threadCounter = 0 # Give number to threads
def __init__(self,host,port):
self.connection = socket.socket() # Create a socket object
self.host = host#socket.gethostname() # Get local machine name
self.port = port # Reserve a port for your service.
def connect(self):
self.connection.connect((self.host, self.port))
# ------------------------ReaderThread------------------------
self.threadCounter += 1
readerThread = ReaderThread(self.threadCounter, "Thread-" + str(self.threadCounter), self.connection)
readerThread.start()
# ------------------------WriterThread------------------------
self.threadCounter += 1
writerThread = WriterThread(self.threadCounter, "Thread-" + str(self.threadCounter), self.connection)
writerThread.start()
# ------------------------ReaderThread------------------------
class ReaderThread(threading.Thread):
def __init__(self, threadID, name, connection):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.connection = connection
def run(self):
global exitFlag
global wait
print("Starting ReaderThread " + str(self.threadID) + " " + self.name)
while exitFlag:
data = self.connection.recv(1024)
if data:
print(data)
if data[0:3] == "BYE":
exitFlag = False
if data[0:3] == "NOW":
self.connection.send("TNX")
wait = False
# ------------------------WriterThread------------------------
class WriterThread(threading.Thread):
def __init__(self, threadID, name, connection):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.connection = connection
def run(self):
global exitFlag
global wait
print("Starting WriterThread " + str(self.threadID) + " " + self.name)
while exitFlag:
if not wait:
request = "Please enter what you want? "
self.connection.send(request.encode())
wait = True
# ------------------------Main Program Functionality------------------------
#用法示例
exitFlag = True
wait = False
client = Client('127.0.0.1',8888)
client.connect()

posted on 2020-01-03 19:32 Benjamin 阅读(255) 评论(0)  编辑 收藏 引用 所属分类: python


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理