使用TCP打包数据

时间:2014-06-23 19:32:00

标签: python sockets tcp

我有一个脚本,它从ADC读取数据,我想通过TCP传输。有问题的两台机器通过以太网连接,我已经有了一个工作的服务器/客户端平台,即我可以发送“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)

#listen用于传入连接    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

1 个答案:

答案 0 :(得分:0)

我还没有对此进行测试,但我很少接触python,但我认为你只能pickle你的数据。类似的东西:

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

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