【问题标题】:Packaging Data with TCP使用 TCP 打包数据
【发布时间】:2014-06-23 19:32:00
【问题描述】:

我有一个脚本,它从我想通过 TCP 传输的 ADC 读取数据。有问题的两台机器通过以太网连接,我已经有了一个工作服务器/客户端平台,即我可以发送“hello world”。我对网络很陌生,想知道传输数据的过程是什么。如何结合使用套接字读取 ADC 值的功能?

服务器:

import socket
import sys

#Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#bind the socket to the port
server_address = ('0.0.0.0', 10000)
print >> sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)

#监听传入连接 sock.listen(1)

while True:
    #wait for connection
    print >> sys.stderr, 'waiting for connection'
    connection, client_address = sock.accept()

try:
    print >> sys.stderr, 'connection from', client_address

    #receive data in small chunks
    while True:
       data = connection.recv(16)
       print >> sys.stderr, 'received "%s"' % data
       if data:
           print >> sys.stderr, 'sending data back to client'
           connection.sendall(data)
       else:
           print >> sys.stderr, 'no more data from', client_address
           break

finally:
    #clean up connection
    connection.close()

客户:

import socket
import sys

#Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


#bind the socket to the port
server_address = ('SERVER_IP', 10000)

print >> sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)

try:
    #send data
    message = 'Transmitting this message . . .'
    print >> sys.stderr, 'sending "%s"' % message
    sock.sendall(message)

    #look for response
    amount_received = 0
    amount_expected = len(message)

        while amount_received < amount_expected:
            data = sock.recv(24)
            amount_received += len(data)
            print >> sys.stderr, 'received "%s"' % data
finally:
        print >> sys.stderr, 'closing socket'
        sock.close()

以及读取我要积分的 ADC 值的函数:

def readadc(adcnum):


        #this function will open the SPI and read it to see the current value
        # this will then be written to a text value
        # using the write_to_file function

    if adcnum > 7 or adcnum < 0:
        return -1
    r = spi.xfer2([1,8 + adcnum << 4,0])

    adcout = ((r[1] & 3) << 8) + r[2]
    return adcout


while True:
    Inp1 = int(round(readadc(0)/10.24))  # defines Inp1 as an integer to be read in
    count = count +1
    time.sleep(0.1)                      # puts the system to sleep for 0.1 seconds

【问题讨论】:

  • 发布一些用于发送“hello world”的代码和一些显示您实际尝试发送的数据的代码。
  • 不要使用套接字,而是使用更高级别的框架,除非您有特定的理由要在低级套接字上构建。简单的方法是构建网络服务器、[XML]RPC,或者使用 ZeroMQ(介于前者和 TCP 套接字之间)。
  • TCP 似乎是我一直在阅读的最佳选择,我将提供一些代码示例。

标签: python sockets tcp


【解决方案1】:

我没有测试过这个,我很少接触 python,但我认为你可以 pickle 你的数据。比如:

# Write 
fp = sock.makefile('wb')
pickle.dump(Inp1, fp)

# Read
fp = connection.makefile('rb')
pickle.load(fp)

【讨论】:

    猜你喜欢
    • 2015-06-15
    • 1970-01-01
    • 2015-01-10
    • 2011-01-12
    • 2011-11-01
    • 1970-01-01
    相关资源
    最近更新 更多