仅从s接收一个字节

2024-04-30 02:20:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python编写了一个服务器程序。在

我想找一根绳子,但我只有一个字符! 如何接收字符串?在

def handleclient(connection):                                           
    while True:                             
        rec = connection.recv(200)
        if rec == "help": #when I put help in the client program, rec = 'h' and not to "help"
            connection.send("Help Menu!")


    connection.send(rec)
    connection.close()

def main():
   while True:
        connection, addr = sckobj.accept()   
        connection.send("Hello\n\r")
        connection.send("Message: ")   
        IpClient = addr[0]
        print 'Server was connected by :',IpClient


        thread.start_new(handleclient, (connection,))   

Tags: 字符串sendtruedefhelpconnection字符服务器程序
1条回答
网友
1楼 · 发布于 2024-04-30 02:20:36

使用TCP/IP连接,您的消息可以被分割。它可能一次只发一封信,也可能一次发一整封信——你永远无法确定。在

你的程序需要能够处理这种碎片。要么使用固定长度的数据包(因此您总是读取X字节),要么在每个数据包的开头发送数据的长度。如果只发送ASCII字母,还可以使用特定字符(例如\n)来标记传输结束。在本例中,您将一直阅读直到消息包含\n。在

recv(200)不能保证接收200字节-200只是最大值。在

以下是服务器的外观示例:

rec = ""
while True:
    rec += connection.recv(1024)
    rec_end = rec.find('\n')
    if rec_end != -1:
        data = rec[:rec_end]

        # Do whatever you want with data here

        rec = rec[rec_end+1:]

相关问题 更多 >