📜  在Python中使用多线程进行套接字编程

📅  最后修改于: 2022-05-13 01:55:40.739000             🧑  作者: Mango

在Python中使用多线程进行套接字编程

先决条件: Python中的套接字编程, PythonPython的多线程
Socket Programming -> 它帮助我们将客户端连接到服务器。客户端是消息的发送者和接收者,服务器只是一个监听客户端发送的数据的监听器。
什么是线程?
线程是一个轻量级进程,不需要太多内存开销,它们比进程便宜。
什么是多线程套接字编程?
多线程是在单个进程中同时执行多个线程的过程。
多线程模块:
_thread 模块和线程模块用于Python中的多线程,这些模块有助于同步并为正在使用的线程提供锁。

from _thread import *
import threading

锁对象由->创建

print_lock = threading.Lock()

锁有两种状态,“锁定”或“解锁”。它有两个基本方法acquire() 和release()。当状态解锁时 print_lock.acquire()用于将状态更改为锁定,而print_lock.release()用于将状态更改为解锁。
函数thread.start_new_thread()用于启动一个新线程并返回其标识符。第一个参数是要调用的函数,第二个参数是一个包含参数位置列表的元组。
让我们通过代码来学习客户端-服务器多线程套接字编程——
注意:-该代码适用于 python3。
多线程服务器代码

Python3
# import socket programming library
import socket
 
# import thread module
from _thread import *
import threading
 
print_lock = threading.Lock()
 
# thread function
def threaded(c):
    while True:
 
        # data received from client
        data = c.recv(1024)
        if not data:
            print('Bye')
             
            # lock released on exit
            print_lock.release()
            break
 
        # reverse the given string from client
        data = data[::-1]
 
        # send back reversed string to client
        c.send(data)
 
    # connection closed
    c.close()
 
 
def Main():
    host = ""
 
    # reverse a port on your computer
    # in our case it is 12345 but it
    # can be anything
    port = 12345
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((host, port))
    print("socket binded to port", port)
 
    # put the socket into listening mode
    s.listen(5)
    print("socket is listening")
 
    # a forever loop until client wants to exit
    while True:
 
        # establish connection with client
        c, addr = s.accept()
 
        # lock acquired by client
        print_lock.acquire()
        print('Connected to :', addr[0], ':', addr[1])
 
        # Start a new thread and return its identifier
        start_new_thread(threaded, (c,))
    s.close()
 
 
if __name__ == '__main__':
    Main()


Python
# Import socket module
import socket
 
 
def Main():
    # local host IP '127.0.0.1'
    host = '127.0.0.1'
 
    # Define the port on which you want to connect
    port = 12345
 
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 
    # connect to server on local computer
    s.connect((host,port))
 
    # message you send to server
    message = "shaurya says geeksforgeeks"
    while True:
 
        # message sent to server
        s.send(message.encode('ascii'))
 
        # message received from server
        data = s.recv(1024)
 
        # print the received message
        # here it would be a reverse of sent message
        print('Received from the server :',str(data.decode('ascii')))
 
        # ask the client whether he wants to continue
        ans = input('\nDo you want to continue(y/n) :')
        if ans == 'y':
            continue
        else:
            break
    # close the connection
    s.close()
 
if __name__ == '__main__':
    Main()


Console Window:
socket binded to port 12345
socket is listening
Connected to : 127.0.0.1 : 11600
Bye

客户代码

Python

# Import socket module
import socket
 
 
def Main():
    # local host IP '127.0.0.1'
    host = '127.0.0.1'
 
    # Define the port on which you want to connect
    port = 12345
 
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 
    # connect to server on local computer
    s.connect((host,port))
 
    # message you send to server
    message = "shaurya says geeksforgeeks"
    while True:
 
        # message sent to server
        s.send(message.encode('ascii'))
 
        # message received from server
        data = s.recv(1024)
 
        # print the received message
        # here it would be a reverse of sent message
        print('Received from the server :',str(data.decode('ascii')))
 
        # ask the client whether he wants to continue
        ans = input('\nDo you want to continue(y/n) :')
        if ans == 'y':
            continue
        else:
            break
    # close the connection
    s.close()
 
if __name__ == '__main__':
    Main()
Console Window:
Received from the server : skeegrofskeeg syas ayruahs

Do you want to continue(y/n) :y
Received from the server : skeegrofskeeg syas ayruahs

Do you want to continue(y/n) :n

Process finished with exit code 0