从套接字流中分离并显示位图

时间:2013-02-22 16:18:52

标签: c++

如何从多个图像的连续套接字流中分离和显示位图图像?当只有一个bmp接收时,下面的代码将保存并显示单个图像。当套接字流包含多个位图图像时,如何分离和显示图像(例如BM .... BM .... BM ...)?

DWORD WINAPI CServerDlg::ThreadSocket( LPVOID lpParam )
{
    CServerDlg *pThis = (CServerDlg *)lpParam;

    SOCKET server;

    WSADATA wsaData;
    int wsaret = WSAStartup( MAKEWORD(2,2), &wsaData );
    if( wsaret != 0 )
    {
        return 0;
    }

    sockaddr_in local;
    local.sin_family = AF_INET; //Address family
    local.sin_addr.s_addr = INADDR_ANY; //Wild card IP address
    local.sin_port = htons((u_short)8888); //port to use

    server = socket( AF_INET, SOCK_STREAM, 0 );
    if( server == INVALID_SOCKET )
    {
        return 0;
    }

    if( bind( server, (sockaddr*)&local, sizeof(local) ) != 0 )
    {
        return 0;
    }
    if( listen( server, 10 ) != 0 )
    {
        return 0;
    }

    SOCKET_STREAM_FILE_INFO     StreamFileInfo;
    memset( &StreamFileInfo, 0, sizeof(SOCKET_STREAM_FILE_INFO) );
    SOCKET client;
    sockaddr_in from;
    int fromlen = sizeof( from );
    while( pThis->m_bListen )
    {
        char temp[1024];
        memset( temp, 0, 1024 );
        client = accept( server, (struct sockaddr*)&from, &fromlen );
        int iLen = recv( client, temp, sizeof(SOCKET_STREAM_FILE_INFO), 0 );
        if( iLen == sizeof(StreamFileInfo) )
        {
            memcpy( &StreamFileInfo, temp, sizeof(StreamFileInfo) );
            CFile destFile( StreamFileInfo.szFileTitle, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary);
            UINT dwRead = 0;
            while( dwRead < StreamFileInfo.nFileSizeLow )
            {
                memset(temp,0,1024);
                UINT dw = recv( client, temp, 1024, 0 );
                destFile.Write(temp, dw);
                dwRead += dw;
            }
            destFile.Close();

            pThis->LoadPicture( StreamFileInfo.szFileTitle );   // Display image in a dialog box
        }
        closesocket(client);
    }
    closesocket(server);
    WSACleanup();

    return 0;
} 

2 个答案:

答案 0 :(得分:1)

此处描述的位图格式

http://en.wikipedia.org/wiki/BMP_file_format

在标题中包含文件大小字段。您可以为每个位图读取该内容,并知道当前位图的结尾位置。

答案 1 :(得分:0)

您需要设计一种区分不同图像的协议。

一个简单的发送标题(包含图像的大小(以字节为单位),可能还有图像类型),然后是实际的图像数据就足够了。