程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Multitasking TCP server implemented by Python based on socket

編輯:Python
'''
be based on socket Implementation of the multi tasking version TCP Server side
'''
import socket
import threading
def client_task(client_socket,ip_port):
print(ip_port,' Join the connection ')
# Continue to receive messages from the client
while True:
data=client_socket.recv(1024).decode('gbk')
if len(data)!=0:
print(f' client {ip_port[0]} The message is {data}')
else:
print(f' client {ip_port[0]} Has been disconnected ')
break
send_data=('Hello--'+data).encode('gbk')
client_socket.send(send_data)
if __name__ == '__main__':
server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True)
server_socket.bind(('',7777))
server_socket.listen(128)
# Receive client connections cyclically
while True:
client_socket,ip_port=server_socket.accept() # Will be waiting for the receive connection
t_client=threading.Thread(target=client_task,args=(client_socket,ip_port))
t_client.setDaemon(True)
t_client.start()

Object oriented version

'''
be based on socket Implementation of the multi tasking version TCP Server side ( object-oriented )
'''
import socket
import threading
class SocketServer(object):
def __init__(self, port):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
self.server_socket.bind(('', port))
self.server_socket.listen(128)
def start(self):
# Receive client connections cyclically
while True:
client_socket, ip_port = self.server_socket.accept() # Will be waiting for the receive connection
t_client = threading.Thread(target=self.client_task, args=(client_socket, ip_port))
t_client.setDaemon(True)
t_client.start()
def client_task(self,client_socket, ip_port):
print(ip_port, ' Join the connection ')
# Continue to receive messages from the client
while True:
data = client_socket.recv(1024).decode('gbk')
if len(data) != 0:
print(f' client {ip_port[0]} The message is {data}')
else:
print(f' client {ip_port[0]} Has been disconnected ')
break
send_data = ('Hello--' + data).encode('gbk')
client_socket.send(send_data)
if __name__ == '__main__':
server_socket=SocketServer(7777)
server_socket.start()


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved