下方分別有Server端及Client端的code,
Server端要先執行,
並保持運行狀態,
才能持續接收Client端的訊息請求,
Client端則是傳送一筆訊息給Server端,
告知Server端應該回傳什麼訊息給Client,
那這邊的話,
Client端是要求Server端給予HTTP相關的資訊
Server端
import socketserver
import socket
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip()
print ("{} wrote:".format(self.client_address[0]))
print (self.data)
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = socket.gethostname(), 80
print('HOST: ', HOST)
print('Port: ', PORT)
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
Client端
import socket
import sys
if __name__ == '__main__':
serverHost = 'DESKTOP-40IXG82'
port = 80
try:
#create an AF_INET, STREAM socket (TCP)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Socket Created')
server_ip = socket.gethostbyname(serverHost)
print('IP Address of ' + serverHost + ' is ' + server_ip)
s.connect((server_ip, port))
print('Socket Connected to ' + serverHost + ' on ip ' + server_ip)
message = "GET / HTTP/1.1\r\n\r\n"
bytM = message.encode()
s.sendall(bytM)
print('Message send successfully')
recv = s.recv(4096)
print(recv)
s.close()
except socket.error:
print('Failed!')
sys.exit()
補充1:
訊息encoding及deconding用法
在Python3裡,
不論是Server端還是Client端要傳送訊息時,
會給一個字串訊息,
並且須對此字串做編碼的動作,
才能被送出,
而接收到訊息,
則需要透過解碼的動作,
才可以拿到原來的字串訊息,
Encoding寫法
mess = 'get data'
enMess = mess.encode()
Decoding寫法
data = request.recv(1024).strip()
data.decode()
補充2:
假設Server回傳訊息比較慢約5秒左右,
Clinet端這邊可以設置delay模式來等待,
如藍字部分所示:
Client端-延長訊息接收時間
import socket
import sys
import time
if __name__ == '__main__':
serverHost = 'DESKTOP-40IXG82'
port = 80
try:
#create an AF_INET, STREAM socket (TCP)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Socket Created')
server_ip = socket.gethostbyname(serverHost)
print('IP Address of ' + serverHost + ' is ' + server_ip)
s.connect((server_ip, port))
print('Socket Connected to ' + serverHost + ' on ip ' + server_ip)
message = "GET / HTTP/1.1\r\n\r\n"
bytM = message.encode()
s.sendall(bytM)
print('Message send successfully')
time.sleep(2) #延長2秒
recv = s.recv(4096)
print(recv)
s.close()
except socket.error:
print('Failed!')
sys.exit()
留言列表