Hi.
last night i tried to write a simple tcp server on select model in C for windows machine but there are some problems.
Here is the code:
Code:
#include <stdio.h>
#include <WinSock2.h>
#include <time.h>
main()
{
WSADATA wsadata;
SOCKET ListeningSocket;
SOCKET NewSocket;
SOCKADDR_IN ServerAddr;
SOCKADDR_IN ClientAddr;
FD_SET fdread;
struct timeval time;
int port = 4444;
int size;
int SelectResults;
char RcvBuff[200];
// Initialize Winsock version 2.2
WSAStartup(MAKEWORD(2,2),&wsadata);
// Initialize Socket
ListeningSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
// Initialize Server's SOCKADDR struct
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons(port);
ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
// Bind Socket with SOCKADDR struct.
bind(ListeningSocket,(SOCKADDR *)&ServerAddr,sizeof(ServerAddr));
// Make socket Listening.
listen(ListeningSocket,5);
// Accept connection
size = sizeof(struct sockaddr);
NewSocket = accept(ListeningSocket,(SOCKADDR *)&ClientAddr,&size);
while(1)
{
// Initialize FD_SETS for the select function.
FD_ZERO(&fdread); // Clear the fd_set before select.
FD_SET(NewSocket,&fdread); // Assign Our Socket with fdread set.
// Seting up timer
time.tv_sec = 2; // seconds
time.tv_usec = 5000; // miliseconds
// Select function.
SelectResults = select(0, &fdread, NULL, NULL, &time);
// Checking select's results.
if(SelectResults == SOCKET_ERROR)
{
printf("Hey man we have a problem with select\n");
break;
}
if(SelectResults > 0)
{
// That means we have some readable sockets.
// Checking if our socket (NewSocket) exists in fdread SET.
if(FD_ISSET(NewSocket,&fdread))
{
printf("Our socket exists and here is what it wants to say:\n\n");
// Recieving data from socket
memset(&RcvBuff,0,sizeof(&RcvBuff));
recv(NewSocket,RcvBuff,200,0);
printf("%s\n", RcvBuff);
}
}
}
}
The first problem is that i can not connect a second client on the server.
The second one is that if client send this: "hat" (three letters) everything goes right but if the client send "hato" (four letters) the server prints out :
hato╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠☺
And the third problem is that when i shutdown the client the server prints out until i close it the phrase :
Our socket exists and here is what it wants to say:
Our socket exists and here is what it wants to say:
Our socket exists and here is what it wants to say:
Our socket exists and here is what it wants to say:
Our socket exists and here is what it wants to say:
Our socket exists and here is what it wants to say:
Can anyone help me fix some of these problems ?
Thanks in advance.