python發(fā)送byte數(shù)據(jù)組到tcp的server問題
python發(fā)送byte數(shù)據(jù)組到tcp的server
前一段時(shí)間需要和一個(gè)tcp服務(wù)端進(jìn)行數(shù)據(jù)交互,有約定好的數(shù)據(jù)報(bào)文格式,但是是以十六進(jìn)制形式定義的的,所以在測試數(shù)據(jù)反饋的時(shí)候用python寫了一個(gè)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)
# 作為客戶端,主動(dòng)連接服務(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)可以實(shí)現(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中默認(rèn)是utf-8編碼
# 在udp協(xié)議中使用的sendto() 因?yàn)閡dp發(fā)送的為數(shù)據(jù)報(bào),包括ip port和數(shù)據(jù), # 所以sendto()中需要傳入address,而tcp為面向連接,再發(fā)送消息之前就已經(jīng)連接上了目標(biāo)主機(jī)
#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 = [] # 放每個(gè)客戶端的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é)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python游戲測試工具自動(dòng)化遍歷游戲中所有關(guān)卡
這篇文章主要為大家介紹了python游戲測試工具自動(dòng)化遍歷游戲中所有關(guān)卡示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
Python實(shí)現(xiàn)比較兩個(gè)列表(list)范圍
這篇文章主要介紹了Python實(shí)現(xiàn)比較兩個(gè)列表(list)范圍,本文根據(jù)一道題目實(shí)現(xiàn)解決代碼,本文分別給出題目和解答源碼,需要的朋友可以參考下2015-06-06
一文詳解Python中三元運(yùn)算符的用法以及避坑指南
這篇文章主要為大家詳細(xì)介紹了Python中的三元運(yùn)算符(條件表達(dá)式),這是一種簡潔的條件判斷語法結(jié)構(gòu),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下2026-01-01
使用Python實(shí)現(xiàn)ELT統(tǒng)計(jì)多個(gè)服務(wù)器下所有數(shù)據(jù)表信息
這篇文章主要介紹了使用Python實(shí)現(xiàn)ELT統(tǒng)計(jì)多個(gè)服務(wù)器下所有數(shù)據(jù)表信息,ETL,是英文Extract-Transform-Load的縮寫,用來描述將數(shù)據(jù)從來源端經(jīng)過抽取(extract)、轉(zhuǎn)換(transform)、加載(load)至目的端的過程,需要的朋友可以參考下2023-07-07
Python進(jìn)行MySQL數(shù)據(jù)備份與增刪改查操作實(shí)戰(zhàn)指南
Python是一種強(qiáng)大且易于學(xué)習(xí)的編程語言,這篇文章主要為大家詳細(xì)介紹了mysql數(shù)據(jù)庫備份以及利用pymysql模塊進(jìn)行數(shù)據(jù)庫增刪改查的相關(guān)操作2025-07-07
Python實(shí)現(xiàn)讀取文本文件并轉(zhuǎn)換為pdf
這篇文章主要為大家詳細(xì)介紹了如何使用Python簡便快捷地完成TXT文件到PDF文檔的轉(zhuǎn)換,滿足多樣化的文檔處理需求,感興趣的小伙伴可以參考下2024-04-04
基于Python實(shí)現(xiàn)倒計(jì)時(shí)工具
這篇文章主要為大家詳細(xì)介紹了基于Python實(shí)現(xiàn)倒計(jì)時(shí)工具,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08

