Python多线程Socket网络编程
环境
Python 3.7.6 (Linux)
Python 3.7.4 (Windows)
CentOS Linux release 8.1.1911 (Core)
socket
实现代码
服务器端
其中<port>
为程序监听的端口号,'0.0.0.0'
表示监听来自所有IP客户端的请求,程序接收到客户端请求时与其建立连接
import socket
import threading
class SendThread(threading.Thread):
'''
Description:
send message thread class, inherited from threading.Thread class
Args:
connection:
connect to client
'''
def __init__(self, connection):
threading.Thread.__init__(self)
self.connection = connection
'''
Description:
override method, read from standard input and send message to client
Attributes:
None
Returns:
None
'''
def run(self):
while True:
try:
data = input()
self.connection.send(data.encode('utf-8'))
except Exception as e:
print(e)
break
class ReceiveThread(threading.Thread):
'''
Description:
receive message thread class, inherited from threading.Thread class
Args:
connection:
connect to client
'''
def __init__(self, connection):
threading.Thread.__init__(self)
self.connection = connection
'''
Description:
override method, receive message from connection and output to console
Attributes:
None
Returns:
None
'''
def run(self):
while True:
try:
data = self.connection.recv(1024)
print("\nServer receive data from client: " + data.decode('utf-8'))
except Exception as e:
print(e)
break
if __name__ == "__main__":
server = socket.socket()
server.bind(('0.0.0.0', <port>))
server.listen(5)
connection, address = server.accept()
print("Connect to Client successfully!")
send_thread = SendThread(connection)
receive_thread = ReceiveThread(connection)
send_thread.start()
receive_thread.start()
客户端
其中<host name>
为远程服务器公网IP,<port>
为端口号
import threading
import socket
class SendThread(threading.Thread):
'''
Description:
send message thread class, inherited from threading.Thread class
Args:
connection:
connect to client
'''
def __init__(self, client):
threading.Thread.__init__(self)
self.client = client
'''
Description:
override method, read from standard input and send message to server
Attributes:
None
Returns:
None
'''
def run(self):
while True:
data = input()
self.client.send(data.encode('utf-8'))
class ReceiveThread(threading.Thread):
'''
Description:
receive message thread class, inherited from threading.Thread class
Args:
connection:
connect to client
'''
def __init__(self, client):
threading.Thread.__init__(self)
self.client = client
'''
Description:
override method, receive message from connection and output to console
Attributes:
None
Returns:
None
'''
def run(self):
while True:
data = self.client.recv(1024)
print("Client receive data from server:" + data.decode('utf-8'))
if __name__ == "__main__":
client = socket.socket()
client.connect((<host name>, <port>))
print('Connect to server successfully')
send_thread = SendThread(client)
receive_thread = ReceiveThread(client)
send_thread.start()
receive_thread.start()
测试
服务器端
Hello client, this is server
客户端
Hello server, this is client
最后
- 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!