user1973035
user1973035

Reputation: 33

Sockets - sending image

fp = fopen("image.jpg","rb");
if (!fp)
    exit(1);
fseek(fp,0,SEEK_END); 
len = ftell(fp);
fseek(fp,0,SEEK_SET); 
buf = (char *)malloc(len);
fread(buf,len,1,fp);
fclose(fp);


if (WSAStartup(0x0202,&wsa) != 0)
{
    printf("Error code : %d",WSAGetLastError());
    return 1;
}



if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
    printf("Error code : %d" , WSAGetLastError());
    WSACleanup();
    exit(1);
}


server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );


if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
{
    printf("Error code : %d" , WSAGetLastError());
    closesocket(s);
    WSACleanup();
    exit(EXIT_FAILURE);
}

sprintf(str,"%d",len);
strcpy(message,"HTTP/1.1 200 OK\r\nContent-Length: ");
sprintf(message,"%s %s",message,str);
sprintf(message,"%s %s",message,"\r\nContent-Type: image/jpeg\r\n\r\n");
sprintf(message,"%s %s",message,buf);
sprintf(message,"%s %s",message,"\r\n");

listen(s , 100);

c = sizeof(struct sockaddr_in);

while( (new_socket = accept(s , (struct sockaddr *)&client, &c)) != INVALID_SOCKET )
{
    memset(recvdata,'\0',sizeof(recvdata));
    recv(new_socket,recvdata,2000,0);

    send(new_socket , message , strlen(message) , 0);
}

if (new_socket == INVALID_SOCKET)
{
    printf("Error code : %d" , WSAGetLastError());
    closesocket(s);
    WSACleanup();
    return 1;
}
closesocket(s);
WSACleanup();
return 0;

}

I have a problem with sending image file. This is server side of communication and browser will be client side. When i try to connect to server, server accepts connection and everything is ok. Then i want to send image as response, and it should be showed in browser. Can anyone tell me what is a problem here?

Upvotes: 0

Views: 376

Answers (1)

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84169

Many issues. Just to start:

  • You are not checking return values of system calls (listen(), recv(), send(), etc.), so you don't know about errors, and how much data you sent or received.
  • Printing binary data like from image file here with printf() is a Bad IdeaTM - it will be truncated at the first zero byte, or it might overrun your memory with a lack of such.
  • You are assuming recv() consumes full HTTP request from a client. It might not, so you are breaking HTTP protocol.
  • You are not closing connected client socket in your loop. That is a resource leak.

Upvotes: 2

Related Questions