从套接字只接收一个字节

6

我使用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,))   

1
你是否正在使用非阻塞套接字? - cdarke
2个回答

6

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:]

所以我需要创建一个循环,检查接收到的数据是否等于 \n 然后检查是否包含 "help"。 - programmer
就像我说的,你可以用几种方法来实现。如果你的消息永远不会包含\n,那么你可以将其作为终止符使用。在客户端发送消息时,在消息末尾添加\n,在服务器端读取数据直到看到\n。我在我的答案中添加了一些快速示例代码。 - Tim

0

我解决愚蠢的Embarcadero C++ Builder问题的方法

char RecvBuffer[4096];
boolean first_init_flag = true;
while(true)
{
    int bytesReceived;

    while(true)
    {
        ZeroMemory(RecvBuffer, 4096);
        bytesReceived = recv(clientSocket,(char*) &RecvBuffer, sizeof(RecvBuffer), 0);
        std::cout << "RecvBuffer: " << RecvBuffer << std::endl;
        std::cout << "bytesReceived: " << bytesReceived <<std ::endl;

        if (!std::strcmp(RecvBuffer, "\r\n"))
        {
            if (first_init_flag) {
                first_init_flag = !first_init_flag;
            }
            else
            {
                break;
            }
        }
    }


    if (bytesReceived == SOCKET_ERROR)
    {
        std::cout << "Client disconnected" << std::endl;
        break;
    }
    send(clientSocket, RecvBuffer, bytesReceived + 1, 0);
}

首先,您发送\r\n或ENTER以避免连接握手和第一次数据发送的串联


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接