python發(fā)送byte數(shù)據(jù)組到tcp的server問題
更新時間:2023年09月06日 16:06:05 作者:橙木
這篇文章主要介紹了python發(fā)送byte數(shù)據(jù)組到tcp的server問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
python發(fā)送byte數(shù)據(jù)組到tcp的server
前一段時間需要和一個tcp服務(wù)端進行數(shù)據(jù)交互,有約定好的數(shù)據(jù)報文格式,但是是以十六進制形式定義的的,所以在測試數(shù)據(jù)反饋的時候用python寫了一個byte[]數(shù)據(jù)發(fā)送的tcp clinet端的測試demo
代碼如下:
from socket import *
import struct
import time
import sys
def init(x):#初始化需要發(fā)送的list數(shù)組
lists = [[0]*8 for i in range(7)]#定義list的行列大小
for i in range(7):
lists[i].append(0)#填充0
lists[i][3] = 5
lists[i][4] = int(x)#填充序號
lists[0][7] = 16#填充指令id
lists[1][7] = 17
lists[2][7] = 18
lists[3][7] = 19
lists[4][7] = 20
lists[5][7] = 24
lists[6][7] = 25
return lists
def main():
# 1.創(chuàng)建tcp_client_socket 套接字對象
tcp_client_socket = socket(AF_INET,SOCK_STREAM)
# 作為客戶端,主動連接服務(wù)器較多,一般不需要綁定端口
# 2.連接服務(wù)器
tcp_client_socket.connect(("127.0.0.1",7001))
a = sys.argv[1]
while True:
for i in range(7):
print(init(a)[i])
"""無限循環(huán)可以實現(xiàn)無限發(fā)送"""
# 3.向服務(wù)器發(fā)送數(shù)據(jù)
cmd = init(a)[i]
to_server = ""
for i in range(len(cmd)):
to_server += chr(cmd[i])
print(repr(to_server))
print("發(fā)送的消息為:",to_server.encode())
tcp_client_socket.send(to_server.encode())# 在linux中默認是utf-8編碼
# 在udp協(xié)議中使用的sendto() 因為udp發(fā)送的為數(shù)據(jù)報,包括ip port和數(shù)據(jù), # 所以sendto()中需要傳入address,而tcp為面向連接,再發(fā)送消息之前就已經(jīng)連接上了目標主機
#time.sleep(1)
# 4.接收服務(wù)器返回的消息
recv_data = tcp_client_socket.recv(1024) # 此處與udp不同,客戶端已經(jīng)知道消息來自哪臺服務(wù)器,不需要用recvfrom了
if recv_data:
print("返回的消息為:",recv_data)
else:
print("對方已離線。。")
break
tcp_client_socket.close()
if __name__ == '__main__
main()python tcp server-client
基本思路
- 1、指定IP、端口號;
- 2、綁定;
- 3、開啟監(jiān)聽;
- 4、接受連接創(chuàng)建socket;
- 5、收發(fā)數(shù)據(jù)
tcp_server
# tcp_server
# coding=utf-8
# !/usr/bin/env python
import socket
import time
import threading
serverIP = "0.0.0.0"
serverPort = 10620
clientSocketList = [] # 放每個客戶端的socket
def init_server():
sockServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_addr = (serverIP, serverPort)
sockServer.bind(server_addr)
sockServer.listen(10)
print(server_addr)
print("The server has started, waiting for the client to connect ......")
return sockServer
def accept_client(sockServer):
while True:
time.sleep(0.1)
clientSock, addr = sockServer.accept()
strTime = time.strftime('%Y-%m-%d %H:%M:%S')
strPrint = 'connected from: {}'.format(addr)
strPrint = strTime + strPrint
print(strPrint)
clientSock.setblocking(0)
clientSocketList.append([clientSock, addr])
def server_Send(direction):
while True:
time.sleep(0.1)
try:
sendByte = bytes(direction)
for clientInfo in clientSocketList:
currClient, addr = clientInfo
currClient.sendall(sendByte)
print("to {}, send <{}> ".format(addr, sendByte))
except Exception as e:
clientSocketList.remove(clientInfo)
continue
def server_Recv():
while True:
time.sleep(0.1)
for clientInfo in clientSocketList:
# print(client.getsockname())
# print(client.getpeername())
currClient, addr = clientInfo
try:
dataRecv = currClient.recv(1024)
except Exception as e:
continue
if not dataRecv:
clientSocketList.remove(clientInfo)
print("currClient{} has closeed.\n".format(addr))
continue
try:
direction = float(dataRecv)
strTime = time.strftime('%Y-%m-%d %H:%M:%S')
strRecv = "from {} recv len={}, data={}".format(addr, len(dataRecv), direction)
print(strRecv)
except Exception as e:
print(e)
pass
if __name__ == '__main__':
sockServer = init_server()
threadCheckClient = threading.Thread(target=accept_client, args=(sockServer, )) # 子線程
# threadCheckClient.setDaemon(True)
threadCheckClient.start()
threadSend = threading.Thread(target=server_Recv) # 子線程
# threadSend.setDaemon(True)
threadSend.start()tcp_client
# tcp_client
# coding=utf-8
# !/usr/bin/env python
import socket
import sys, time
from threading import Thread
serverIP = '127.0.0.1'
serverPort = 10620
def init_client():
tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
tcp_client.connect((serverIP, serverPort))
except socket.error:
print('fail to setup socket connection')
return tcp_client
def client_Send(tcp_client):
while True:
time.sleep(0.1)
time.sleep(1)
try:
strTime = time.strftime('%Y-%m-%d %H:%M:%S')
strTime = str(12345.5678909)
sendBytes =strTime.encode()
tcp_client.sendall(sendBytes)
print(sendBytes)
except Exception as e:
break
def client_Recv(tcp_client):
while True:
time.sleep(0.1)
try:
dataRecv = tcp_client.recv(1024) # 到這里程序繼續(xù)向下執(zhí)行
except Exception as e:
continue
if not dataRecv:
break
else:
strTime = time.strftime('%Y-%m-%d %H:%M:%S')
strRecv = "from server recv len={}, data={}".format( len(dataRecv), dataRecv)
strPrint = strTime + strRecv
print(strPrint)
if __name__ == "__main__":
tcp_client = init_client()
threadSend = Thread(target=client_Send, args=(tcp_client, )) # 子線程
threadSend.start()總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python游戲測試工具自動化遍歷游戲中所有關(guān)卡
這篇文章主要為大家介紹了python游戲測試工具自動化遍歷游戲中所有關(guān)卡示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06
使用Python實現(xiàn)ELT統(tǒng)計多個服務(wù)器下所有數(shù)據(jù)表信息
這篇文章主要介紹了使用Python實現(xiàn)ELT統(tǒng)計多個服務(wù)器下所有數(shù)據(jù)表信息,ETL,是英文Extract-Transform-Load的縮寫,用來描述將數(shù)據(jù)從來源端經(jīng)過抽取(extract)、轉(zhuǎn)換(transform)、加載(load)至目的端的過程,需要的朋友可以參考下2023-07-07
Python進行MySQL數(shù)據(jù)備份與增刪改查操作實戰(zhàn)指南
Python是一種強大且易于學(xué)習(xí)的編程語言,這篇文章主要為大家詳細介紹了mysql數(shù)據(jù)庫備份以及利用pymysql模塊進行數(shù)據(jù)庫增刪改查的相關(guān)操作2025-07-07
Python實現(xiàn)讀取文本文件并轉(zhuǎn)換為pdf
這篇文章主要為大家詳細介紹了如何使用Python簡便快捷地完成TXT文件到PDF文檔的轉(zhuǎn)換,滿足多樣化的文檔處理需求,感興趣的小伙伴可以參考下2024-04-04

