Hi Guys,
I wrote a little program that must stay always listen in port 2282 and wait
for message. :)
I done it based in my knowledge of socket for linux and some documentation
for windows by ms.
My code is:
#include<stdio.h>
#include <winsock2.h>
#define MINHA_PORTA 2282
#define BACKLOG 5
int main(int argc, char *argv[]){
struct sockaddr_in local;
struct sockaddr_in remoto;
int MeuSocket, NovoSocket,tamanho, i, nbytes;
char buff[1024]="\0";
WORD wVersion;
WSADATA wStart;
fd_set master;
fd_set read_fds;
wVersion = MAKEWORD(2, 0);
if(WSAStartup(wVersion,&wStart) != 0) {
return;
}
MeuSocket = socket(AF_INET,SOCK_STREAM,0);
if ( MeuSocket < 0 ){
perror("Socket ");
exit(1);
}
for (i=0;i<8;i++) {
local.sin_zero[i]=0;
}
local.sin_family = AF_INET;
local.sin_port = htons(MINHA_PORTA);
local.sin_addr.s_addr = INADDR_ANY;
bind(MeuSocket,(struct sockaddr *)&local, sizeof(struct sockaddr));
listen(MeuSocket,BACKLOG);
tamanho = sizeof(struct sockaddr_in);
while(1){
if((NovoSocket = accept(MeuSocket,(struct sockaddr *)&remoto, &tamanho)) ==
1){
perror("Accept ");
exit(1);
}
FD_ZERO(&master);
FD_SET(NovoSocket,&master);
read_fds = master;
if(select(NovoSocket+1, &read_fds, NULL, NULL, NULL) == -1){
perror("select");
exit(1);
}
if (FD_ISSET(NovoSocket, &read_fds)){
nbytes = 0;
if ((nbytes = (recv(NovoSocket,buff,sizeof(buff),0))) == -1){
perror("read");
exit(1);
}
fprintf(stdout,"%s",buff);
}
}
close(NovoSocket);
return(0);
}
It compile and works, the porblem is that is only receive a packet by
connection.
For example, I can open 5 connections and send data, but only the first DATA
of each packet will be received.
If it was a program for linux, i know that i will be able to solve this
problem with a fork() + for().
But fork() isn't avaible to Windows. :/
I tryed only with for(), but in this case, i received all data from a
connection, but i can receive only one connection.
Someone know how to do it in windows ??
If u can help, i will be very heap. :)
Be free to modify the code.
Best Regards.
[ ]'s
|