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)制形式定義的的,所以在測(cè)試數(shù)據(jù)反饋的時(shí)候用python寫了一個(gè)byte[]數(shù)據(jù)發(fā)送的tcp clinet端的測(cè)試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)#填充序號(hào)
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 套接字對(duì)象
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])
"""無(wú)限循環(huán)可以實(shí)現(xiàn)無(wú)限發(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)知道消息來(lái)自哪臺(tái)服務(wù)器,不需要用recvfrom了
if recv_data:
print("返回的消息為:",recv_data)
else:
print("對(duì)方已離線。。")
break
tcp_client_socket.close()
if __name__ == '__main__
main()python tcp server-client
基本思路
- 1、指定IP、端口號(hào);
- 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計(jì)算三角函數(shù)之a(chǎn)tan()方法的使用
這篇文章主要介紹了用Python計(jì)算三角函數(shù)之a(chǎn)tan()方法的使用,是Python入門的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-05-05
Django 通過JS實(shí)現(xiàn)ajax過程詳解
這篇文章主要介紹了Django 通過JS實(shí)現(xiàn)ajax過程詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07
python利用腳本輕松實(shí)現(xiàn)ssh免密登陸配置
這篇文章主要為大家詳細(xì)介紹了python如何利用腳本輕松實(shí)現(xiàn)ssh免密登陸配置,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-12-12
Django使用unittest模塊進(jìn)行單元測(cè)試過程解析
這篇文章主要介紹了Django使用unittest模塊進(jìn)行單元測(cè)試過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08
python操作注冊(cè)表的方法實(shí)現(xiàn)
Python提供了winreg模塊,可以用于操作Windows注冊(cè)表,本文就來(lái)介紹一下python操作注冊(cè)表的方法實(shí)現(xiàn),主要包括打開注冊(cè)表、讀取注冊(cè)表值、寫入注冊(cè)表值和關(guān)閉注冊(cè)表,具有一定的參考價(jià)值,感興趣的可以了解一下2023-08-08
python用opencv將標(biāo)注提取畫框到對(duì)應(yīng)的圖像中
這篇文章主要介紹了python用opencv將標(biāo)注提取畫框到對(duì)應(yīng)的圖像中,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08
PyTorch中關(guān)于tensor.repeat()的使用
這篇文章主要介紹了PyTorch中關(guān)于tensor.repeat()的使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11

