欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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中默認(rèn)是utf-8編碼
        # 在udp協(xié)議中使用的sendto() 因為udp發(fā)送的為數(shù)據(jù)報,包括ip port和數(shù)據(jù),           # 所以sendto()中需要傳入address,而tcp為面向連接,再發(fā)送消息之前就已經(jīng)連接上了目標(biāo)主機
        #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計算三角函數(shù)之a(chǎn)tan()方法的使用

    用Python計算三角函數(shù)之a(chǎn)tan()方法的使用

    這篇文章主要介紹了用Python計算三角函數(shù)之a(chǎn)tan()方法的使用,是Python入門的基礎(chǔ)知識,需要的朋友可以參考下
    2015-05-05
  • Django 通過JS實現(xiàn)ajax過程詳解

    Django 通過JS實現(xiàn)ajax過程詳解

    這篇文章主要介紹了Django 通過JS實現(xiàn)ajax過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-07-07
  • python利用腳本輕松實現(xiàn)ssh免密登陸配置

    python利用腳本輕松實現(xiàn)ssh免密登陸配置

    這篇文章主要為大家詳細介紹了python如何利用腳本輕松實現(xiàn)ssh免密登陸配置,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-12-12
  • Pandas替換NaN值的方法實現(xiàn)

    Pandas替換NaN值的方法實現(xiàn)

    本文主要介紹了Pandas替換NaN值的方法實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-01-01
  • Django使用unittest模塊進行單元測試過程解析

    Django使用unittest模塊進行單元測試過程解析

    這篇文章主要介紹了Django使用unittest模塊進行單元測試過程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-08-08
  • Python實現(xiàn)雙向鏈表基本操作

    Python實現(xiàn)雙向鏈表基本操作

    這篇文章主要為大家詳細介紹了Python實現(xiàn)雙向鏈表基本操作,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-05-05
  • python操作注冊表的方法實現(xiàn)

    python操作注冊表的方法實現(xiàn)

    Python提供了winreg模塊,可以用于操作Windows注冊表,本文就來介紹一下python操作注冊表的方法實現(xiàn),主要包括打開注冊表、讀取注冊表值、寫入注冊表值和關(guān)閉注冊表,具有一定的參考價值,感興趣的可以了解一下
    2023-08-08
  • python用opencv將標(biāo)注提取畫框到對應(yīng)的圖像中

    python用opencv將標(biāo)注提取畫框到對應(yīng)的圖像中

    這篇文章主要介紹了python用opencv將標(biāo)注提取畫框到對應(yīng)的圖像中,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-08-08
  • PyTorch中關(guān)于tensor.repeat()的使用

    PyTorch中關(guān)于tensor.repeat()的使用

    這篇文章主要介紹了PyTorch中關(guān)于tensor.repeat()的使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • Python決策樹分類算法學(xué)習(xí)

    Python決策樹分類算法學(xué)習(xí)

    這篇文章主要為大家詳細介紹了Python決策樹分類算法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-12-12

最新評論