Sending files over winsock/linux sockets
Hey, im making a simple program that sends/receives files, my code sends text files but when it comes to binary it starts to bug, code:
static void
send_event(conn,file)
void *conn;
void *file;
{
FILE *f;
char *buffer;
int32_t block_size;
int32_t size;
size_t __read;
ConnectionQueue *q;
f = (FILE *)file;
q = (ConnectionQueue *)conn;
block_size = conf_getint("transfer:block_size");
if (block_size <= 1 || block_size > 1024)
{
abort();
return;
}
buffer = (char *)MyMalloc(block_size);
if (!q || !f)
return;
fseek(f开发者_JS百科,0L,SEEK_END);
size = ftell(f);
if (size == 0L)
{
send_socket(q->conn,"RECEIVE: 302 FSE");
return;
}
fseek(f,0,SEEK_SET);
while (true)
{
if (q->abort)
{
send_socket(q->conn,"RECEIVE: File transfer aborted\n");
if (f)
fclose(f);
f = NULL;
MyFree(buffer);
return;
}
__sleep(100);
__read = fread(buffer,sizeof(char),512,f);
if (__read <= 0)
{
send_socket(q->conn,"RECEIVE: EOF\n");
break;
}
if (*buffer == '\0')
{
send_socket(q->conn,"RECEIVE: EOF\n");
break;
}
send_socket(q->conn,"RECEIVE: %s\n",buffer);
}
send_socket(q->conn,"RECEIVE: 915 EOF\n");
fclose(f);
f = NULL;
MyFree(buffer);
}
FIXED: Please check my answer \/
What's with the K&R syntax and the void *
parameters?
static void send_event( ConnectionQueue * conn, FILE * file) {
....
On binary vs text, typically this is because you open a file using "r" and not "rb" as mode.
__read = fread(buffer,sizeof(char),512,f);
You should use block_size
and not 512
there.
if (*buffer == '\0')
...
send_socket(q->conn,"RECEIVE: %s\n",buffer);
Your "binary files" could contain 0's - that's not a good EOF marker, and if you're using strlen
in send_socket
you'll get your data cut off at the first 0 in your buffer.
this fixed it -> Send binary file in HTTP response using C sockets
精彩评论