I'm trying to make a stream server.
This first attempt sends a mp3 file to the media that request http://127.0.0.1:7000/test.mp3
The only that server does is to read and print the whole request(blue code), send the answer (red code) and finally stream the file(green code).
Server runs once.
Here is the list with my problems-questions :
1) Is something missing from my code ?
2) Why after the end of server's execution i have to wait a minute(or less) for another one ? I get this error "Address already in use"
3) Why media-player/browser sometimes open the file and sometimes not. (I mean that, i run server and i request through firefox the file and i get it. The next execution will not work and server won't stream file)
4) How can i achieve a real streaming because this one just loads the file to media-player/browser and after stores or play it.
*This is not the final code but as i test network C for first time i want to learn by testing.
Thanks in advance
Code:#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#define BACKLOG SOMAXCONN
#define BUFSIZE 1024
int main(void)
{
char buffer[BUFSIZE];
int socketFd;
int newSocketFd;
int port=7000;
int res;
FILE *stream;
struct sockaddr_in server;
struct sockaddr_in client;
struct hostent *rem;
socklen_t clientLength;
//Create socket
socketFd = socket(PF_INET,SOCK_STREAM,0);
if (socketFd == -1)
{
fprintf(stderr,"Error creating socket : ");
perror("");
return -1;
}
//Binding the above socket
server.sin_family = PF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(port);
res = bind(socketFd,(struct sockaddr *)&server,sizeof(struct sockaddr_in));
if(res < 0)
{
fprintf(stderr,"Error binding socket : ");
perror("");
close(socketFd);
return -1;
}
//Listening for connections
res = listen(socketFd,BACKLOG);
if(res < 0)
{
fprintf(stderr,"Error listening socket : ");
perror("");
close(socketFd);
return -1;
}
printf("Server ready to accept clients\n");
clientLength = sizeof(struct sockaddr_in);
newSocketFd = accept(socketFd, (struct sockaddr *)&client, &clientLength);
if(newSocketFd < 0)
{
fprintf(stderr,"Fail to accept connection : ");
perror("");
}
printf("Connection established\n");
recv(newSocketFd,buffer,BUFSIZE,0); printf("%s",buffer);
send(newSocketFd,"HTTP/1.0 200 OK\r\n",18,1);
send(newSocketFd,"Sever: musicstreamer v1.0\r\n",28,1);
send(newSocketFd,"Connection: close\r\n",20,1);
send(newSocketFd,"Content-Type: audio/mpeg\r\n\r\n",26,1);
stream = fopen("test.mp3","rb");
while(fread(buffer,1,1,stream) > 0)
send(newSocketFd,buffer,1,0);
fclose(stream);
close(newSocketFd);
close(socketFd);
return 0;
}