Python多线程Socket网络编程

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

最后

  • 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值