【问题标题】:Only receiving one byte from socket只从套接字接收一个字节
【发布时间】:2012-10-25 03:30:17
【问题描述】:

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

【问题讨论】:

  • 你在使用非阻塞套接字吗?

标签: python sockets socketserver


【解决方案1】:

我对愚蠢的 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 以进行转义连接握手和第一次数据发送

【讨论】:

    【解决方案2】:

    使用 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 然后检查“帮助”。
    • 正如我所说,您可以通过几种方式做到这一点。如果您的消息永远不会包含\n,您可以将其用作终止符。在客户端的消息末尾发送它,并在服务器中读取数据,直到看到\n。我在答案中添加了一些快速示例代码。
    猜你喜欢
    • 2016-02-26
    • 2011-07-11
    • 2016-01-27
    • 2016-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多