socketserver實現併發(Python)

2021-09-26 09:08:44 字數 1751 閱讀 2746

server類:處理鏈結

request類:處理通訊

(基於tcp)

#服務端

import socketserver

class

myserver

(socketserver.baserequesthandler)

:def

handle

(self)

:print

(self.request)

#conn

print

(self.client_address)

#addr

while

true

:try

:#收訊息

data = self.request.recv(

1024)if

not data:

break

print

('收到客戶端的訊息是'

, data)

#發訊息

self.request.sendall(data.upper())

except exception as e:

print

(e)break

if __name__ ==

'__main__'

: s = socketserver.threadingtcpserver(

('127.0.0.1'

,8000

), myserver)

#多執行緒tcp服務端(==通訊迴圈)

#s = socketserver.forkingtcpserver(('127.0.0.1', 8000), myserver) #多程序

s.serve_forever(

)#永遠服務(==鏈結迴圈)

#客戶端

from socket import

*ip_port =

('127.0.0.1'

,8000

)back_log =

5buffer_size =

1024

tcp_client = socket(af_inet, sock_stream)

tcp_client.connect(ip_port)

while

true

: msg =

input

('>>:'

).strip()if

not msg:

continue

if msg ==

'quit'

:break

tcp_client.send(msg.encode(

'utf-8'))

data = tcp_client.recv(buffer_size)

print

('收到服務端發來的訊息:'

, data.decode(

'utf-8'))

tcp_client.close(

)

執行結果:

socketserver實現併發

使用socketserver模組實現多執行緒或多程序併發 tcp服務端 import socketserver class myserver socketserver.baserequesthandler defhandle self print conn是 self.request 建立的鏈結,s...

socketserver實現併發操作

服務端 當無端埠有問題時,改個埠 socketserver 實現併發 import socketserver class myserver socketserver.baserequesthandler def handle self 內建handle方法 print conn is self.re...

2 socketserver實現併發

1 tcp socketserver伺服器端 coding utf 8 import socketserver class myserver socketserver.baserequesthandler defhandle self print conn is self.request print...