仅从套接字接收一个字节

时间:2012-11-05 09:57:49

标签: python sockets socketserver

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

2 个答案:

答案 0 :(得分: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:]

答案 1 :(得分: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 以进行转义连接握手和第一次数据发送