图像通过套接字C ++服务器和C#客户端发送

时间:2014-03-16 19:06:42

标签: c# c++ image sockets

我正在使用C#开发一个Windows应用商店应用程序。我想建立TCP连接以从桌面服务器接收图像(现在)。服务器是C ++。

我有一个客户端C ++来测试这个功能,它运行得很好。现在我想要的是一个类似的客户端,但在C#中。我尝试转换它,但没有运气,我试图使用相同的逻辑,但我有大量的错误,并删除了一切。

感谢帮助,谢谢。

C ++服务器

int size = 8192;     //image size
char* bufferCMP;
bufferCMP = (char*)malloc(sizeof(char)* size);
FILE *p_file;
p_file = fopen("C:\\Program Files\\img1.png", "rb");
fread(bufferCMP, 1, size, p_file);
fclose(p_file);


int chunkcount = size / DEFAULT_BUFLEN;
int lastchunksize = size - (chunkcount * DEFAULT_BUFLEN);
int fileoffset = 0;

printf("Sending actual Chunk");
while (chunkcount > 0)
{
    iResult = send(ClientSocket, bufferCMP + (fileoffset * DEFAULT_BUFLEN), DEFAULT_BUFLEN, 0);
    fileoffset++;
    chunkcount--;

    if (iResult != DEFAULT_BUFLEN)
    {
        printf("Sending Buffer size <> Default buffer length  ::: %d\n");
    }
    else
    {
        printf("Sending Buffer size = %d \n", iResult, fileoffset);
    }
}

printf("Sending last Chunk", lastchunksize);
iResult = send(ClientSocket, bufferCMP + (fileoffset * DEFAULT_BUFLEN), lastchunksize, 0);

`

C ++客户端(要转换为C#)

int size = 8192;


int FileCounter = 0;
bool flg = true;
char * fileComplete;
char * filesizeBuffer;

FILE *temp;

int receiveBuffer = 0;
int desiredRecBuffer = size;
//int desiredRecBuffer = DEFAULT_BUFLEN ; 
fileComplete = (char*)malloc(sizeof(char)* size);

while (desiredRecBuffer > 0)
{
    iResult = recv(ConnectSocket, fileComplete + receiveBuffer, desiredRecBuffer, 0);
    //iResult = recv( ClientSocket, fileComplete + receiveBuffer , fileSize , 0 );

    if (iResult < 1)
    {
        printf("Reveive Buffer Error  %d \n", WSAGetLastError());
    }
    else
    {
        receiveBuffer += iResult;
        desiredRecBuffer = size - receiveBuffer;
        printf("Reveived Data size :  %d \n", desiredRecBuffer);

    }
}

FILE *File = fopen("C:\\Users\\amirk_000\\Pictures\\img1b.png", "wb");
fwrite(fileComplete, 1, size, File);
//flg = true;
free(fileComplete);
fclose(File);

1 个答案:

答案 0 :(得分:0)

C#客户端套接字的完整示例可用at MSDN

修改给定的SocketSendReceive方法,将接收到的缓冲区(bytesReceived数组)写入文件流。

以下内容应该这样做:

    using (var file = File.OpenWrite("myimage.png"))
    {
        do
        {
            bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);
            file.Write(bytesReceived, 0, bytes);
        }
        while (bytes > 0);
    }