1、tcp_socketserver伺服器端:
#-*- coding:utf-8 -*-
import
socketserver
class
myserver(socketserver.baserequesthandler):
defhandle(self):
print('
conn is:
', self.request)
print('
addr is:
', self.client_address)
while
true:
try:
data = self.request.recv(1024)
ifnot data:break
print('
收到的客戶端訊息:
', data)
self.request.sendall(data.upper())
except
exception as e:
(e)
break
if__name__ == '
__main__':
s = socketserver.threadingtcpserver(('
127.0.0.1
', 8080), myserver) #
多執行緒#
s = socketserver.forkingtcpserver(('127.0.0.1', 8080), myserver) #多程序
(s.server_address)
(s.requesthandlerclass)
(s.socket)
(myserver)
s.serve_forever()
2、tcp_socketserver客戶端:
#-*- coding:utf-8 -*-
from socket import *host = '
127.0.0.1'#
伺服器的主機號和埠號
port = 8080bufsiz = 1024addr =(host, port)
tcpclisock = socket(af_inet, sock_stream) #
tcp客戶端套接字
tcpclisock.connect(addr) #
主動連線到tcp伺服器
while
true:
data = input('
>>')
ifnot data:#
如果本客戶端傳送的訊息是空的,則跳出此次迴圈
continue
tcpclisock.send(data.encode(
'utf-8'))
data =tcpclisock.recv(bufsiz)
print(data.decode('
utf-8'))
tcpclisock.close()
3、udp_socketserver伺服器端:
#-*- coding:utf-8 -*-
import
socketserver
class
myserver(socketserver.baserequesthandler):
defhandle(self):
(self.request)
print('
收到的客戶端訊息:
', self.request[0])
#發訊息
self.request[1].sendto(self.request[0].upper(), self.client_address)
if__name__ == '
__main__':
s = socketserver.threadingudpserver(('
127.0.0.1
', 8080), myserver) #
多執行緒 s.serve_forever()
4、udp_socketserver客戶端:
#-*- coding:utf-8 -*-
from socket import *ip_port = ('
127.0.0.1
', 8080)
bufsize = 1024udpclisocket =socket(af_inet, sock_dgram)
while
true:
msg = input('
>>:
').strip()
ifnot msg:continue
udpclisocket.sendto(msg.encode(
'utf-8
'), ip_port)
back_msg, addr =udpclisocket.recvfrom(bufsize)
print(back_msg.decode('
utf-8
'), addr)
5、socketserver模組分析
socketserver模組中分為兩大類:server類(解決連線問題)、request類(解決通訊問題)
(1)server類:
(2)request類
socketserver實現併發
使用socketserver模組實現多執行緒或多程序併發 tcp服務端 import socketserver class myserver socketserver.baserequesthandler defhandle self print conn是 self.request 建立的鏈結,s...
socketserver實現併發(Python)
server類 處理鏈結 request類 處理通訊 基於tcp 服務端 import socketserver class myserver socketserver.baserequesthandler def handle self print self.request conn print ...
socketserver實現併發操作
服務端 當無端埠有問題時,改個埠 socketserver 實現併發 import socketserver class myserver socketserver.baserequesthandler def handle self 內建handle方法 print conn is self.re...