Reputation: 33
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
Reputation: 84169
Many issues. Just to start:
listen()
, recv()
, send()
, etc.), so you don't know about errors, and how much data you sent or received.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.recv()
consumes full HTTP request from a client. It might not, so you are breaking HTTP protocol.Upvotes: 2