hey guys!
first time here... hope to stay for long! cheers to everyone!
I found this example - this server serves only one client at a time,
what do I need to change to it allows multiple clients to connect to?
Code:
#ifndef _WINSOCKAPI_
#define _WINSOCKAPI_
#endif
#include <windows.h>
#include <winsock2.h>
#include <stdio.h>
// Declare the sockets we use.
SOCKET listeningSocket;
SOCKET connectedSocket;
int InitSockets(void)
{
struct sockaddr *servAddr;
struct sockaddr_in *inetServAddr;
int error = 0;
// Create the socket.
listeningSocket = socket(AF_INET, SOCK_STREAM, 0);
if(listeningSocket == INVALID_SOCKET) {
printf("error: socket() failed");
return –1;
}
// Allocate memory for the address structure and set it to zero.
servAddr = (struct sockaddr *) malloc(sizeof(sockaddr));
memset((char *) servAddr, 0, sizeof(sockaddr));
// Fill the address structure.
servAddr->sa_family = (u_short) AF_INET;
inetServAddr = (struct sockaddr_in *) servAddr;
inetServAddr->sin_port = htons((u_short) 9009);
// Bind the address information to the socket.
error = bind(listeningSocket, servAddr, sizeof(sockaddr));
if(error == SOCKET_ERROR) {
printf("error: bind() failed");
free(servAddr);
return –1;
}
free(servAddr);
servAddr = NULL;
// Listen for incoming connections. Queue only one connection.
error = listen(listeningSocket, 1);
if(error == SOCKET_ERROR) {
printf("error: listen() failed");
return –1;
}
// Accept the connection. Accept is a blocking function.
connectedSocket = accept(listeningSocket, NULL, NULL);
if(connectedSocket == INVALID_SOCKET)
void ServerProcess(void)
{
int connectionOpen;
char buf[2];
connectionOpen = 1;
// Loop as long as connection is open.
while(connectionOpen) {
// Read the incoming data from the connected socket.
if(recv(connectedSocket, buf, 2, 0)) {
// Set the received letter to uppercase and
// make sure the string ends after that by setting the next
// byte to NULL.
buf[0] = toupper(buf[0]);
buf[1] = '\0';
printf("Got message from client: %s\n", buf);
// Send the feedback.
if(send(connectedSocket, buf, 2, 0) == SOCKET_ERROR) {
connectionOpen = 0;
}
}
else {
closesocket(connectedSocket);
connectionOpen = 0;
}
}
}
int main(void) {
if(NET_WinSockInitialize() != 0) {
printf("Critical error, quitting\n");
return –1;
}
if(InitSockets() != 0) {
printf("Critical error, quitting\n");
WSACleanup();
return –1;
}
ServerProcess();
WSACleanup();
return 0;
}
If client code is needed - I can supply! Thanks!
regards.