Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Initialize Winshock 2.2
- WSAStartup(MAKEWORD(2,2),&wsaData);
- // Create a new socket to make a client connection.
- ConnectSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
- // Initialize Servers SOCKADDR_IN
- ServerAddr.sin_family = AF_INET;
- ServerAddr.sin_port = htons(port);
- ServerAddr.sin_addr.s_addr = inet_addr(server_address);
- // Clear the fd sets
- FD_ZERO(&fdread);
- FD_ZERO(&BackUpfdread);
- FD_ZERO(&fdwrite);
- FD_ZERO(&BackUpfdwrite);
- // Asign the ListeningSocket with fdread and fdwrite.
- FD_SET(ConnectSocket,&fdread);
- FD_SET(ConnectSocket,&fdwrite);
- // Set as maxDescriptor ListeningSocket.
- maxDescriptor = ConnectSocket;
- // Setup timer.
- timer.tv_sec = 2;
- timer.tv_usec = 5000;
- // Make a connection to the server with socket s.
- connect(ConnectSocket, (SOCKADDR *) &ServerAddr, sizeof(ServerAddr));
- // Send the username to server.
- send(ConnectSocket,username,strlen(username),0);
- // Receive Welcome Message From Server (If any..)
- RecvBytes = recv(ConnectSocket,RecvBuff,sizeof(RecvBuff),0);
- if(RecvBytes > 0)
- {
- printf("%s",RecvBuff);
- // Cleaning the Receive Buffer
- memset(RecvBuff,0,sizeof(RecvBuff));
- }
- // Main loop starts here
- for(; ;)
- {
- memset(SentBuff, 0, sizeof(SentBuff));
- printf("Write: ");
- gets_s(SentBuff, sizeof(SentBuff));
- // Copy the fdread into BackUpfdread and fdwrite to BackUpfdwrite.
- BackUpfdread = fdread;
- BackUpfdwrite = fdwrite;
- SelectResults = select(maxDescriptor+1,&BackUpfdread,&BackUpfdwrite,NULL,&timer);
- if(SelectResults == -1)
- {
- perror("Client-select() error!\n");
- exit(1);
- }
- //printf("Client-select is OK\n");
- //Check if we have some data to read.
- for(i=0;i<=maxDescriptor;i++)
- { // #1
- if(FD_ISSET(i,&BackUpfdread))
- { // #2
- if(i == ConnectSocket)
- { // #3
- RecvBytes = recv(i, RecvBuff, sizeof(RecvBuff), 0);
- if(RecvBytes > 0) { printf("%s\n",RecvBuff);
- // Cleaning the Receive Buffer
- memset(RecvBuff,0,sizeof(RecvBuff));
- }
- } // #3 end here
- } // #2 end here
- if(FD_ISSET(i,&BackUpfdwrite))
- {
- if(i == ConnectSocket)
- {
- SentBytes = send(i, SentBuff,sizeof(SentBuff),0);
- // Cleaning the Sent Buffer
- memset(SentBuff,0,sizeof(SentBuff));
- }
- }
- } // #1 end here
- } // Main loop ends here
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement