仅从插座接收一个字节



我使用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("Hellonr")
        connection.send("Message: ")   
        IpClient = addr[0]
        print 'Server was connected by :',IpClient

        thread.start_new(handleclient, (connection,))   

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

我解决了愚蠢的embarcadero C 建造者

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, "rn"))
        {
            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或输入以进行逃生串联握手和第一个数据发送

相关内容

最新更新