如何从套接字接收数据,处理并在python中发回数据?

时间:2014-01-03 19:58:49

标签: python sockets

我有以下代码:

import socket               # Import socket module
import sys

s = socket.socket()         # Create a socket object

host = ''  # Get local machine name
port = 1234                # Reserve a port for your service.

s.connect((host, port))

while 1:
    data = s.recv(1024)
    print ' data ' , data
    d = data.split('?')  # parsing values from server 
    if len(d) < 2: 
         # if does not contain ?, do nothing
         continue
    else: 
         a = d[0]
         b = d[1].replace('\n', '')
         # check how a compares to b, and send response accordingly
         if (a > b):
            s.send('1')
         elif (a == b):
            s.send('2')
         else: 
            s.send('3')

s.close()                     # Close the socket when done

如果没有我的处理代码,如果我只发送一个随机值,它就可以正常工作。但是使用上面的代码,我只能解析第一组行,然后停止。 (我假设它关闭了套接字或其他东西?)

来自套接字的数据看起来像'1? 23'或'23? 1'等,它期望一个确定两个数字如何相关的响应。

相比之下,如果我有这段代码:

import socket               # Import socket module
import sys

s = socket.socket()         # Create a socket object

host = ''  # Get local machine name
port = 1234                # Reserve a port for your service.

s.connect((host, port))

backlog = ''

while 1:
    data = s.recv(1024)
    sp = data.split('\n')
    if len(sp) < 2:
        backlog += data
        continue
    line = backlog + sp[0]
    backlog = sp[1]
    data = line
    print ' data ' , data
    if not data:
        break
    s.send ('2')

s.close()                     # Close the socket when done

此代码将产生“正确!”的服务器响应或'不正确......再试一次!'取决于它是对还是错。

1 个答案:

答案 0 :(得分:0)

您似乎认为每次read()来电都会得到一整行。那是错的。

你应该将你的输入分成几行,只有你有一个完整的行,你才能继续。

backlog = ''
while 1:
    data = s.recv(1024)
    # do we have a line break?
    sp = data.split('\n')
    if len(sp) < 2:
        # no, we haven't...
        backlog += data
        continue
    # yes, we have.
    line = backlog + sp[0] # first part is the now complete line.
    backlog = sp[1] # 2nd part is the start of the new line.
    print ' line ' , line
    d = line.split('?')  # parsing values from server 
    if len(d) < 2: 
         # if does not contain ?, do nothing
         continue
    else: 
         a = int(d[0]) # we want to compare numbers, not strings.
         b = int(d[1])
         # check how a compares to b, and send response accordingly
         if (a > b):
            s.send('1')
         elif (a == b):
            s.send('2')
         else: 
            s.send('3')

尝试现在发生的事情。

我遇到的另一个问题是服务器到底想要什么?真的只有一个字节?或者更确切地说是'1\n''2\n''3\n'