python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python发送byte数据组到tcp的server

python发送byte数据组到tcp的server问题

作者:橙木

这篇文章主要介绍了python发送byte数据组到tcp的server问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

python发送byte数据组到tcp的server

前一段时间需要和一个tcp服务端进行数据交互,有约定好的数据报文格式,但是是以十六进制形式定义的的,所以在测试数据反馈的时候用python写了一个byte[]数据发送的tcp clinet端的测试demo

代码如下:

from socket import *
import struct
import time
import sys
def init(x):#初始化需要发送的list数组
    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.创建tcp_client_socket 套接字对象
    tcp_client_socket = socket(AF_INET,SOCK_STREAM)
    # 作为客户端,主动连接服务器较多,一般不需要绑定端口
    # 2.连接服务器
    tcp_client_socket.connect(("127.0.0.1",7001))
    a = sys.argv[1]
    while True:
        for i in range(7):
            print(init(a)[i])
            """无限循环可以实现无限发送"""
            # 3.向服务器发送数据
            cmd = init(a)[i]
            to_server = ""
            for i in range(len(cmd)):
                to_server += chr(cmd[i])
            print(repr(to_server))
            print("发送的消息为:",to_server.encode())
            tcp_client_socket.send(to_server.encode())# 在linux中默认是utf-8编码
        # 在udp协议中使用的sendto() 因为udp发送的为数据报,包括ip port和数据,           # 所以sendto()中需要传入address,而tcp为面向连接,再发送消息之前就已经连接上了目标主机
        #time.sleep(1)
        # 4.接收服务器返回的消息
            recv_data = tcp_client_socket.recv(1024)  # 此处与udp不同,客户端已经知道消息来自哪台服务器,不需要用recvfrom了
            if recv_data:
                print("返回的消息为:",recv_data)
            else:
                print("对方已离线。。")
                break
    tcp_client_socket.close()
if __name__ == '__main__
	main()

python tcp server-client

基本思路

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)  # 到这里程序继续向下执行
        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()

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文