I have a problem in case of multiple clients socket programming in c++. Actually I have downloaded a source code for server side that echo the message to the clients. Also I have a simple client code. Everything works perfectly as long as there is only one client connected to the server. But when the other client connects, the server echo the message to both of them but, in the client side it prints in different order. Indeed it wait for user to enter the input message and then print out the received message. But I want it to be print it as soon as the message is received. For better description of the problem, the output of chat between two clients connected to the server is mentioned bellow. Also the codes of server and client are attached at the end.
in the Bob cmd:
Pleas insert your message: Bob: hello alice.
The recieved message:Bob: hello alice.
Pleas insert your message: Bob: how is everything?
The recieved message:Alice: hello bob.
Pleas insert your message: Bob: everything is perfect!
The recieved message:Bob: how is everything?Alice: it is fine, and you?
Pleas insert your message:
in the alice cmd:
Pleas insert your message: Alice: hello bob.
The recieved message:Bob: hello alice.
Pleas insert your message: Alice: it is fine, and you?
The recieved message:Alice: hello bob.Bob: how is everything?
Pleas insert your message: Alice: cool!
The recieved message:Alice: it is fine, and you?Bob: everything is perfect!
Pleas insert your message:
and the codes:
/*
TCP Echo server example in winsock
Live Server on port 8888
*/
#include<stdio.h>
#include<winsock2.h>
#pragma comment(lib, "ws2_32.lib") //Winsock Library
int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET master , new_socket , client_socket[30] , s;
struct sockaddr_in server, address;
int max_clients = 30 , activity, addrlen, i, valread;
//size of our receive buffer, this is string length.
int MAXRECV = 1024;
//set of socket descriptors
fd_set readfds;
//1 extra for null character, string termination
char *buffer;
char msg[10] = "salam";
buffer = (char*) malloc((MAXRECV + 1) * sizeof(char));
for(i = 0 ; i < 30;i++)
{
client_socket[i] = 0;
}
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
exit(EXIT_FAILURE);
}
printf("Initialised.\n");
//Create a socket
if((master = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
exit(EXIT_FAILURE);
}
printf("Socket created.\n");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );
//Bind
if( bind(master ,(struct sockaddr *)&server , sizeof(server)) ==
SOCKET_ERROR)
{
printf("Bind failed with error code : %d" , WSAGetLastError());
exit(EXIT_FAILURE);
}
puts("Bind done");
//Listen to incoming connections
listen(master , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
addrlen = sizeof(struct sockaddr_in);
while(TRUE)
{
//clear the socket fd set
FD_ZERO(&readfds);
//add master socket to fd set
FD_SET(master, &readfds);
//add child sockets to fd set
for ( i = 0 ; i < max_clients ; i++)
{
s = client_socket[i];
if(s > 0)
{
FD_SET( s , &readfds);
}
}
//wait for an activity on any of the sockets, timeout is NULL , so wait
indefinitely
activity = select( 0 , &readfds , NULL , NULL , NULL);
if ( activity == SOCKET_ERROR )
{
printf("select call failed with error code : %d" , WSAGetLastError());
exit(EXIT_FAILURE);
}
//If something happened on the master socket , then its an incoming connection
if (FD_ISSET(master , &readfds))
{
if ((new_socket = accept(master , (struct sockaddr *)&address, (int *)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
//inform user of socket number - used in send and receive commands
printf("New connection , socket fd is %d , ip is : %s , port : %d \n" , new_socket , inet_ntoa(address.sin_addr) , ntohs(address.sin_port));
//send( new_socket , msg , valread , 0 );
send( new_socket, msg, (int)strlen(msg), 0 );
//add new socket to array of sockets
for (i = 0; i < max_clients; i++)
{
if (client_socket[i] == 0)
{
client_socket[i] = new_socket;
printf("Adding to list of sockets at index %d \n" , i);
break;
}
}
}
//else its some IO operation on some other socket :)
for (i = 0; i < max_clients; i++)
{
s = client_socket[i];
//if client presend in read sockets
if (FD_ISSET( s , &readfds))
{
//get details of the client
getpeername(s , (struct sockaddr*)&address , (int*)&addrlen);
//Check if it was for closing , and also read the incoming message
//recv does not place a null terminator at the end of the string (whilst printf %s assumes there is one).
valread = recv( s , buffer, MAXRECV, 0);
if( valread == SOCKET_ERROR)
{
int error_code = WSAGetLastError();
if(error_code == WSAECONNRESET)
{
//Somebody disconnected , get his details and print
printf("Host disconnected unexpectedly , ip %s , port %d \n" , inet_ntoa(address.sin_addr) , ntohs(address.sin_port));
//Close the socket and mark as 0 in list for reuse
closesocket( s );
client_socket[i] = 0;
}
else
{
printf("recv failed with error code : %d" , error_code);
}
}
if ( valread == 0)
{
//Somebody disconnected , get his details and print
printf("Host disconnected , ip %s , port %d \n" , inet_ntoa(address.sin_addr) , ntohs(address.sin_port));
//Close the socket and mark as 0 in list for reuse
closesocket( s );
client_socket[i] = 0;
}
//Echo back the message that came in
else
{
//add null character, if you want to use with printf/puts or other string handling functions
buffer[valread] = '\0';
printf("%s:%d - %s \n" , inet_ntoa(address.sin_addr) , ntohs(address.sin_port), buffer);
//for (int j=0;j<4;j++) {
send( client_socket[0] , buffer , valread , 0 );
send( client_socket[1] , buffer , valread , 0 );
//printf("%d",client_socket[j]);
//}
memset(buffer,'\0',sizeof(buffer));
}
}
}
}
closesocket(s);
WSACleanup();
return 0;
}
/*
* Client
*
* Created on: May 31, 2017
* Author: Bamshad
*/
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x501
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "8888"
int __cdecl main(int argc, char **argv)
{
WSADATA wsaData;
SOCKET ConnectSocket;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
char sendbuf[1000];
char recvbuf[DEFAULT_BUFLEN];
int iResult, activity;
int recvbuflen = DEFAULT_BUFLEN;
// Validate the parameters
if (argc != 2) {
printf("usage: %s server-name\n", argv[0]);
return 1;
}
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
//printf("%d\n",ConnectSocket);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
while(TRUE) {
cout << "Lotfan paiam khod ra vared konid: ";
cin.getline(sendbuf,1000);
send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
memset(sendbuf,'\0',sizeof(sendbuf));
recv(ConnectSocket, recvbuf, recvbuflen, 0);
cout << "paiam dariaft:" << recvbuf <<endl;
memset(recvbuf,'\0',sizeof(recvbuf));
}
return 0;
}
I also tried the following code in client side. But still it does not work!
while(TRUE) {
FD_ZERO(&fds); //Clearing the set of descriptors
//FD_SET(fileno(stdin), &fds); //Adding Keyboard to set of descriptors
FD_SET(ConnectSocket,&fds); //Adding Socket to the set of descriptors
activity = select( 0 , &fds , NULL , NULL , NULL);
if ( activity == SOCKET_ERROR )
{
printf("select call failed with error code : %d" , WSAGetLastError());
exit(EXIT_FAILURE);
}
if(FD_ISSET(ConnectSocket,&fds)) {
recv(ConnectSocket, recvbuf, recvbuflen, 0);
cout << "paiam dariaft:" << recvbuf <<endl;
memset(recvbuf,'\0',sizeof(recvbuf));
fflush(stdout);
}
//looking if there is user input from keyboard (0 is for stdin)
if(!_kbhit()) {
//fflush(stdout);
cin.getline(sendbuf,1000);
send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
memset(sendbuf,'\0',sizeof(sendbuf));
}
Related
I'm new to programming, but I'm trying to use C++ to create a TCP server with Winsock which will send a list of all the host's files and directories to the client using dirent. So far the code creates the server, lists all of its directories, and sends the name of only one of them to the client. I can't figure out why only one directory name is being sent, despite all of them being listed on the server's computer.
The 1st code block creates the socket. The issue seems to be in the 2nd block
#include<io.h>
#include<stdio.h>
#include<winsock2.h>
#include <iostream>
#include <dirent.h>
#include <sys/types.h>
#include <string>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET s , new_socket;
struct sockaddr_in server , client;
int c;
char *message;
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
}
printf("Socket created.\n");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );
//Bind
if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d" , WSAGetLastError());
}
puts("Bind done");
//Listen to incoming connections
listen(s , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
new_socket = accept(s , (struct sockaddr *)&client, &c);
if (new_socket == INVALID_SOCKET)
{
printf("accept failed with error code : %d" , WSAGetLastError());
}
puts("Connection accepted");
This is what lists & sends the directories.
//List directory
DIR *dr;
struct dirent *en;
dr = opendir("."); //open all or present directory
if (dr) {
while ((en = readdir(dr)) != NULL) {
printf("%s\n", en->d_name); //print all directory name
message = ("%s\n", en->d_name); //Problem line?
}
closedir(dr); //close all directory
}
send(new_socket , message , strlen(message) , 0);
getchar();
closesocket(s);
WSACleanup();
return 0;
}
I'd really appreciate any help understanding the issue and how to fix it.
I edited the 2nd block of code shown above, and this ended up working.
DIR *dr;
struct dirent *en;
dr = opendir("."); //open all or present directory
if (dr) {
while ((en = readdir(dr)) != NULL) {
printf("%s\n", en->d_name);
char buffer[300];
sprintf(buffer, "%s\n", en->d_name); //saves info to buffer
send(new_socket, buffer, strlen(buffer), 0); //sends the buffer as a message
}
closedir(dr); //close all directory
}
send(new_socket , message , strlen(message) , 0);
getchar();
closesocket(s);
WSACleanup();
return 0;
}
Here is my client-server code which works only for a single user at a time and the client can send as many messages as he wants.
I show the received message at the server and its reply (which is actually reverse of it) - and also the message "message sent".
At client side I show the input message and the server reply: "message got"
But there is a problem in my code: when I try to send multiple messages I get the right output at server side but not at client side, which is only "message got", but after that puts function it doesn't print any output to std-out. I have tried many things but I haven't found a way to do it.
Is there any flushing to std-out or am I missing something?
Please tell me.
server code::::::
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc , char *argv[])
{
int socket_desc , client_sock , c , read_size;
struct sockaddr_in server , client;
char client_message[2000];
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
puts("Socket created");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 42969 );
//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
//print the error message
perror("bind failed. Error");
return 1;
}
puts("bind done");
//Listen
listen(socket_desc , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
while(1)
{
//accept connection from an incoming client
client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c);
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
puts("Connection accepted");
pid_t p=fork();
if(p==0)
{
close(socket_desc);
//Receive a message from client
while( (read_size = recv(client_sock , client_message , sizeof(client_message) , 0)) > 0 )
{
puts(client_message);
char message[20000];
int i,j=0;
for(i=strlen(client_message)-1;i>=0;i--)
message[j++]=client_message[i];
message[j]='\0';
puts(message);
//Send the message back to client
if( send(client_sock , message , sizeof(message),0)>0)
puts("message sent");
// memset(client_message,'\0',sizeof(client_message));
//memset(message,'\0',sizeof(message));
}
if(read_size == 0)
{
puts("Client disconnected");
fflush(stdout);
}
else if(read_size == -1)
{
perror("recv failed");
}
close(client_sock);
exit(1);
}
}
close(socket_desc);
return 0;
}
client code::::
#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<stdlib.h>
int main(int argc , char *argv[])
{
int sock;
struct sockaddr_in server;
// char message[1000] ,
char server_reply[2000];
//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
printf("Could not create socket");
}
puts("Socket created");
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons (42969 );
//Connect to remote server
if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
{
perror("connect failed. Error");
return 1;
}
puts("Connected\n");
//keep communicating with server
while(1)
{
printf("Enter message : ");
char message[1000];
scanf("%s" , message);
//Send some data
if( send(sock , message , sizeof(message) , 0) < 0)
{
puts("Send failed");
return 1;
}
//Receive a reply from the server
if( recv(sock , server_reply , sizeof(server_reply) , 0) > 0)
{
puts("message got");
}
puts("Server reply :");
puts(server_reply);
fflush(stdout);
//memset(server_reply,'\0',sizeof(server_reply));
// memset(message,'\0',sizeof(message));
}
close(sock);
return 0;
}
There are different flaws in this code.
Server side:
you accept socket client_sock in a loop, but only close it in the child: you are leaking socket descriptors -> parent should have also close(client_sock);
client send a message of max size 1000, that server reads in a buffer of size 2000. Fine till here. But you use strlen to find the useful part and send back 2000 bytes (meaning you are sending garbage).
Client side:
you read a string from stdin with scanf into a buffer or size 1000. Ok. But then you send 1000 byte, the message and garbage.
you have no message delimitation. So first message could need many read (in fact if needs at least 2 since you currently send 2000 bytes and read it by chunks of 1000!)
You are mixing size of buffer, string length, and number of bytes sent/received. In server, you should use the number of bytes received and never output more then it, of if you know the the message is null terinated, never output more than its length. And if you want to exchange more than one message, use a delimiting strategy (ending with null (uncommon) or with \n, of send first one or 2 bytes containing the size).
You have problem at this place in server side code:
if( send(client_sock , message , sizeof(message),0)>0)
puts("message sent");
You must replace:
if( send(client_sock , message , strlen(message) + 1,0)>0)
puts("message sent");
I have a problem related with client/server communication via socket when I do consecutive send and after that a recv on client. Example:
Case A:
Client Server
send(...);----------->While(recv(...)>0){
send(...);-----------> print(message);
send(...);----------->}
recv(...);----------->Send(...);
The server receives the 3 messages and send the last answer, but the recv on client failed with SOCKET_ERROR with WSAGetLastError() value of 10060.
The only way to make this case to work is when I add a shutdown(...,SD_SEND) after the last send on client.
Why the case A have this behaviour? and why it works only when I add the shutdown() command?
But if I do:
Case B:
Client Server
send(...);----------->While(recv(...)>0){
recv(...);-----------> send(...);
send(...);-----------> ...
recv(...);-----------> ...
send(...);-----------> ...
recv(...);----------->}
It works fine, server/client receives and send each message.
Here is the code for case A:
Client:
#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define DEFAULT_BUFLEN 1024
#define DEFAULT_PORT "27015"
int main() {
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
ADDRINFOA *ptr = NULL, *result = NULL, hints;
char *ans, *sendbuf = "message\0";
char recvbuf[1024];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
ans=new char[1024];
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
printf("--> Initializing Winsock...\n*** Version: %s\n", wsaData.szDescription);
if (iResult != 0) {
printf("*** Could not initialize Socket.\n*** Error code: %d", iResult);
return 1;
}
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result);
printf("--> Setting server address...\n");
printf("--> local ip: 127.0.0.1 at port: %s...\n",DEFAULT_PORT);
if ( iResult != 0 ) {
printf("*** Error in setting server address.\n*** Error code: %d", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {
// Create a SOCKET for connecting to server
printf("--> Creating client socket object...\n");
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("*** Error creating socket.\n*** Error code: %d\n",WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}
if(setsockopt(ConnectSocket, SOL_SOCKET, SO_RCVTIMEO, (char *)new int(1000), sizeof(int))){
WSACleanup();
//strcpy(recvbuf, "EX_95");
return -5; // Error setting recv timeout.
}
// Connect to server.
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
printf("*** Client ready *** \n\n");
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("*** Unable to connect to server!\n");
WSACleanup();
return 1;
}
// Send an initial buffer
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR) {
printf("*** Send failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("<-- Bytes Sent: %ld\n", iResult);
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR) {
printf("*** Send failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("<-- Bytes Sent: %ld\n", iResult);
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR) {
printf("*** Send failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("<-- Bytes Sent: %ld\n", iResult);
// shutdown the connection since no more data will be sent
/*iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}*/
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
printf("Bytes received: %d\n", iResult);
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
// cleanup
closesocket(ConnectSocket);
WSACleanup();
system("pause");
return 0;
}
Server:
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#include <iostream>
#include <Winsock2.h>
#include <Ws2tcpip.h>
#include <string>
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
const char* DEFAULT_PORT = "27015";
const int DEFAULT_BUFLEN = 1024;
using namespace std;
int main(){
//Connection Variables.
WSADATA wsaData;
ADDRINFOA *result = NULL, hints;
SOCKADDR *clientInfo = NULL;
int iResult;
//Receive Variables.
char recvBuff[DEFAULT_BUFLEN];
int recvBuffLen = DEFAULT_BUFLEN;
int iSendResult;
//Server/Client sockets.
SOCKET ListenSocket = INVALID_SOCKET; //SOCKET for the server to listen for client connections.
SOCKET ClientSocket = INVALID_SOCKET;
//Initialize Winsock
iResult = WSAStartup( MAKEWORD( 2, 2 ), &wsaData );
printf("--> Initializing Winsock...\n*** Version: %s\n", wsaData.szDescription);
if ( iResult != 0 ){
printf("*** Could not initialize Socket.\n*** Error code: %d", iResult);
return 1;
}
//Initialize hints allocated memory.
ZeroMemory( &hints, sizeof( hints ) );
hints.ai_family = AF_INET; //AF_INET is used to specify the IPv4 address family.
hints.ai_socktype = SOCK_STREAM; //SOCK_STREAM is used to specify a stream socket.
hints.ai_protocol = IPPROTO_TCP; //IPPROTO_TCP is used to specify the TCP protocol.
hints.ai_flags = AI_PASSIVE; //AI_PASSIVE The socket address will be used in a call to the bind function.
printf("--> Getting address info from server...\n");
iResult = getaddrinfo( NULL, DEFAULT_PORT, &hints, &result );
if( iResult != 0 ){
printf("*** Error in getting address info from server.\n*** Error code: %d", iResult);
WSACleanup();
return 2;
}
printf("--> Creating server socket object...\n");
//printf("Create socket to ip: %s at port: %s\n", inet_ntoa(((SOCKADDR_IN*)(result->ai_addr))->sin_addr),DEFAULT_PORT);
ListenSocket = socket( result->ai_family, result->ai_socktype, result->ai_protocol );
if( ListenSocket == INVALID_SOCKET ){
printf("*** Error creating socket.\n*** Error code: %d\n",WSAGetLastError());
freeaddrinfo( result );
WSACleanup();
return 3;
}
//BIND()->Associates a local address to a socket.
printf("--> Bind listen object to local ip: 127.0.0.1 at port: %s...\n",DEFAULT_PORT);
iResult = bind( ListenSocket, result->ai_addr, result->ai_addrlen );
if( iResult == SOCKET_ERROR ){
printf("*** Binding failed.\n*** Error code: %d\n", WSAGetLastError());
closesocket( ListenSocket );
freeaddrinfo( result );
WSACleanup();
return 4;
}
freeaddrinfo(result);
printf("*** Server ONLINE: Listening...\n\n");
iResult = listen( ListenSocket, SOMAXCONN );
if( iResult == SOCKET_ERROR ){
printf("*** Failed start listening.\n*** Error code: %d\n",WSAGetLastError());
closesocket( ListenSocket );
freeaddrinfo( result );
WSACleanup();
return 5;
}
for(;1;){
ClientSocket = accept( ListenSocket,clientInfo, NULL );
if( ClientSocket == INVALID_SOCKET ){
printf("*** Failed accepting connection from client.\n*** Error code: %d\n",WSAGetLastError());
continue;
}
else{
printf("--> Connection accepted from client.\n");
iResult=1;
while(iResult > 0){
iResult = recv( ClientSocket, recvBuff, recvBuffLen, 0 );
if( iResult > 0 ){
printf("--> Message received: %s\n--> Total: %d\n", recvBuff, iResult);
}
}
iSendResult = send( ClientSocket, "Answer\0", DEFAULT_BUFLEN, 0 );
if( iSendResult == SOCKET_ERROR ){
printf("*** Sending data failed.\n*** Error code: %d\n",WSAGetLastError());
continue;
}
else{
printf("--> Sent: %d bytes\n", iSendResult);
}
printf("*** Closing connection... \n\n");
iResult = shutdown( ClientSocket, SD_BOTH );
if( iResult == SOCKET_ERROR ){
printf("*** Shutdown client failed.\nError code: %d\n",WSAGetLastError());
closesocket( ClientSocket );
WSACleanup();
return 9;
}
}
}
closesocket( ClientSocket );
WSACleanup();
system("pause");
return 0;
}
Thanks in advance!!!!
Nicolas Miranda S.
The server is blocked inside the recv call when the client waits for the response and thus cannot send anything. Your receiver timeout is 1 second, so after 1 second the client generates a timeout error (WSAETIMEDOUT == 10060).
When you do the shutdown, you only specify SD_SEND, so the connection is not closed, but it causes the server to exit recv, and it is therefore able to send the response.
Note: recv will block until something is received for a stream socket (SOCK_STREAM). You should look at the select() function to see how you can "peek" whether there is data available before calling recv.
Here is an example of using select:
fd_set fds;
timeval tv;
tv.tv_sec = 5000;
fds.fd_count = 1;
fds.fd_array[0] = ClientSocket;
int select_result = select(1, &fds, NULL, NULL, &tv);
If select_result == 0, there was a timeout. Otherwise one of the sockets in fd_set is ready with data. Here there's just one and it was specified as a readfds in the select call.
You need to re-arrange the app so that you have some event (receive the third message, for example, or some timeout without anything received, or something in the message itself) that causes the server to send the response. You can use a second thread for responses but that's beyond what I can show in a short answer.
Communication between a server and a clients works, but the server don't forward the client messages to the other connected client's, but only to the sender.
i want the server react to incoming messages by broadcasting them to all clients like a chat system, but keep my command system without sharring it with all clients, but with with sender.
down below is the sources:
server
/*server*/
#define WIN32_LEAN_AND_MEAN
#include <iostream>
#include <string>
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <process.h>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define PORT "3490"
#define SERVER "localhost"
#include <time.h>
WSADATA wsa;
SOCKET s , new_socket;
struct sockaddr_in server , client;
int c;
char *message;
std::string line;
DWORD WINAPI ProcessClient (LPVOID lpParameter)
{
SOCKET AcceptSocket = (SOCKET) lpParameter;
// Send and receive data.
int bytesSent;
int bytesRecv = SOCKET_ERROR;
char sendbuf[2000]="";
char sendbuf2[2000]="";
char recvbuf[2000]="";
char timebuf[128];
sprintf(sendbuf, "Hello, it's a test server at %s:%d (commands: 1, 2, exit)\n", SERVER, PORT);
bytesSent = send( AcceptSocket, sendbuf, strlen(sendbuf), 0);
if (bytesSent == SOCKET_ERROR)
{
printf( "Error at send hello: %ld\n", WSAGetLastError());
goto fin;
}
while (1)
{
_strtime( timebuf );
ZeroMemory (recvbuf, sizeof(recvbuf));
bytesRecv = recv( AcceptSocket, recvbuf, 32, 0);
printf( "%s Client said: %s\n", timebuf, recvbuf);
sprintf(sendbuf, "%s Client said: %s\n", timebuf, recvbuf);
bytesSent = send( AcceptSocket, sendbuf, strlen(sendbuf), 0);
if (strcmp(recvbuf, "1") == 0)
{
sprintf(sendbuf, "You typed ONE\n");
//printf("Sent '%s'\n", sendbuf);
bytesSent = send( AcceptSocket, sendbuf, strlen(sendbuf), 0);
if (bytesSent == SOCKET_ERROR)
{
printf( "Error at send: %ld\n", WSAGetLastError());
goto fin;
}
}
else if (strcmp(recvbuf, "2") == 0)
{
sprintf(sendbuf, "You typed TWO\n");
//printf("Sent '%s'\n", sendbuf);
bytesSent = send( AcceptSocket, sendbuf, strlen(sendbuf), 0);
if (bytesSent == SOCKET_ERROR)
{
printf( "Error at send: %ld\n", WSAGetLastError());
goto fin;
}
}
else if (strcmp(recvbuf, "exit") == 0)
{
printf( "Client has logged out\n", WSAGetLastError());
goto fin;
}
else
{
// sprintf(sendbuf, "unknown command\n");
//printf("Sent '%s'\n", sendbuf);
// bytesSent = send( AcceptSocket, sendbuf, strlen(sendbuf), 0);
if (bytesSent == SOCKET_ERROR)
{
// printf( "Error at send: %ld\n", WSAGetLastError());
goto fin;
}
}
}
fin:
printf("Client processed\n");
closesocket(AcceptSocket);
return 0;
}
int main(int argc , char *argv[])
{
std::cout << ("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
std::cout << ("Failed. Error Code : %d",WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
std::cout << ("Could not create socket : %d" , WSAGetLastError());
}
std::cout << ("Socket created.\n");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 3490 );
//Bind
if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
{
std::cout << ("Bind failed with error code : %d" , WSAGetLastError());
exit(EXIT_FAILURE);
}
puts("Bind done");
//Listen to incoming connections
listen(s , 3);
//Accept and incoming connection
std::cout << ("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
while(true){
while((new_socket = accept(s , (struct sockaddr *)&client, &c)) != INVALID_SOCKET) {
// Create a new thread for the accepted client (also pass the accepted client socket).
printf( "Client Connected.\n");
DWORD dwThreadId;
CreateThread (NULL, 0, ProcessClient, (LPVOID) new_socket, 0, &dwThreadId);
}
}
if (new_socket == INVALID_SOCKET)
{
std::cout << ("accept failed with error code : %d" , WSAGetLastError());
return 1;
}
closesocket(s);
WSACleanup();
return 0;
}
client
/*client*/
#define WIN32_LEAN_AND_MEAN
#pragma comment(lib,"ws2_32.lib")
#include <iostream>
#include <process.h>
#include <string>
#include <winsock2.h>
SOCKET Socket;
#define SERVER "localhost"
int PORT = 3490;
std::string line;
bool chat = false;
class Buffer
{
public:
int ID;
char Message[256];
}sbuffer;
int ClientThread()
{
char buffer[2000]= "";
for(;; Sleep(10))
{
if(recv(Socket, buffer, sizeof(sbuffer), NULL)!=SOCKET_ERROR)
{
strncpy(sbuffer.Message, buffer, sizeof(sbuffer.Message));
std::cout << "<Client:" << sbuffer.ID << ":> " << sbuffer.Message <<std::endl;
ZeroMemory (buffer, sizeof(buffer));
}
}
return 0;
}
int main(void)
{
WSADATA WsaDat;
if(WSAStartup(MAKEWORD(2,2),&WsaDat)!=0)
{
std::cout<<"Winsock error - Winsock initialization failed\r\n";
WSACleanup();
system("PAUSE");
return 0;
}
// Create our socket
Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(Socket==INVALID_SOCKET)
{
std::cout<<"Winsock error - Socket creation Failed!\r\n";
WSACleanup();
system("PAUSE");
return 0;
}
// Resolve IP address for hostname
struct hostent *host;
if((host=gethostbyname(SERVER))==NULL)
{
std::cout<<"Failed to resolve hostname.\r\n";
WSACleanup();
system("PAUSE");
return 0;
}
// Setup our socket address structure
SOCKADDR_IN SockAddr;
SockAddr.sin_port=htons(PORT);
SockAddr.sin_family=AF_INET;
SockAddr.sin_addr.s_addr=*((unsigned long*)host->h_addr);
// Attempt to connect to server
if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr))!=0)
{
std::cout<<"Failed to establish connection with server\r\n";
WSACleanup();
system("PAUSE");
return 0;
}
// If iMode!=0, non-blocking mode is enabled.
u_long iMode=1;
ioctlsocket(Socket,FIONBIO,&iMode);
// Main loop
for(;;)
{
// Display message from server
char buffer[1000];
memset(buffer,0,999);
int inDataLength=recv(Socket,buffer,1000,0);
std::cout<<buffer;
CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE) ClientThread, NULL, NULL, NULL);
for(;; Sleep(10))
{
std::string buffer;
std::getline(std::cin, buffer);
if (send(Socket, buffer.c_str(), buffer.length(), NULL) < 1){
}
}
int nError=WSAGetLastError();
if(nError!=WSAEWOULDBLOCK&&nError!=0)
{
std::cout<<"Winsock error code: "<<nError<<"\r\n";
std::cout<<"Server disconnected!\r\n";
// Shutdown our socket
shutdown(Socket,SD_SEND);
// Close our socket entirely
closesocket(Socket);
break;
}
Sleep(1000);
}
WSACleanup();
system("PAUSE");
return 0;
}
Please help me fix it, i'm new into socket's. Show me how to do as i'm going understand better with code and it will also be usefull to others who might need it in the future.
If you need the server to communicate with multiple clients, then you need some kind of collection of all the connected clients. Then it's easy to send to all connections, or send to all connection but the originating connection.
How to do it will differ vastly between C and C++, but for C++ look into structures and std::vector.
In pseudo-code it would be something like this:
while (run_server)
{
poll_all_connections();
if (have_new_connection())
{
accept_new_connection();
add_connection_in_collection();
}
else
{
for (connection in all_connections())
{
if (have_input(connection))
{
input = read_from_connection(connection);
for (send_to in all_connections())
write_to_connection(connection, input)
}
}
}
}
If you implement the above pseudo-code, then input from any connection will be sent to all connections.
Don't forget to remove a connection from the collection if the connection is broken (error or disconnect.)
You have to maintain a list of all the client socket connections then send the data to each client one by one.
or you can use threading to implement this as follows :-
Server-thread()
{
while(true)
{
/// Accept Connection in ClientSocket.
HandleClient-Thread(ClientSocket) ; // launch a thread for each client .
}
}
HandleClient-Thread(ClientSocket)
{
// handle this client here
}
i'm trying make asynchronous server listener with C++ i'm new in c++ but i must do this project , i'm web developer (PHP) but PHP can't make async connections + he is very poor language for big amount of connections... i can write simple listener without asynchronous but now i have problem with "CreateThread"... for example if client has been connected console gives me result about this + sniffer can fix it... after 10 sec client must send me again same packet with different data. my console does not gives me result about that packet but sniffer can see that packet... please if anyone can see my problem explain me ... (sorry for my bad english :D )
#include <winsock2.h>
#include <windows.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
DWORD WINAPI SocketHandler(void*);
int main(int argv, char** argc){
//The port you want the server to listen on
int host_port = 7878;
//Initialize socket support WINDOWS ONLY!
unsigned short wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 || ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2 )) {
fprintf(stderr, "Could not find useable sock dll %d\n",WSAGetLastError());
}
//Initialize sockets and set any options
int hsock;
int * p_int ;
hsock = socket(AF_INET, SOCK_STREAM, 0);
if(hsock == -1){
printf("Error initializing socket %d\n",WSAGetLastError());
}
p_int = (int*)malloc(sizeof(int));
*p_int = 1;
if( (setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char*)p_int, sizeof(int)) == -1 )||
(setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char*)p_int, sizeof(int)) == -1 ) ){
printf("Error setting options %d\n", WSAGetLastError());
free(p_int);
}
free(p_int);
//Bind and listen
struct sockaddr_in my_addr;
my_addr.sin_family = AF_INET ;
my_addr.sin_port = htons(host_port);
memset(&(my_addr.sin_zero), 0, 8);
my_addr.sin_addr.s_addr = INADDR_ANY ;
if( bind( hsock, (struct sockaddr*)&my_addr, sizeof(my_addr)) == -1 ){
fprintf(stderr,"Error binding to socket, make sure nothing else is listening on this port %d\n",WSAGetLastError());
}
if(listen( hsock, 10) == -1 ){
fprintf(stderr, "Error listening %d\n",WSAGetLastError());
}
//Now lets to the server stuff
int* csock;
sockaddr_in sadr;
int addr_size = sizeof(SOCKADDR);
while(true){
printf("waiting for a connection\n");
csock = (int*)malloc(sizeof(int));
if((*csock = accept( hsock, (SOCKADDR*)&sadr, &addr_size))!= INVALID_SOCKET ){
printf("Received connection from %s",inet_ntoa(sadr.sin_addr));
CreateThread(0,0,&SocketHandler, (void*)csock , 0,0);
}
else{
fprintf(stderr, "Error accepting %d\n",WSAGetLastError());
}
}
}
DWORD WINAPI SocketHandler(void* lp){
int *csock = (int*)lp;
char buffer[1024];
int buffer_len = 1024;
int bytecount;
memset(buffer, 0, buffer_len);
if((bytecount = recv(*csock, buffer, buffer_len, 0))==SOCKET_ERROR){
fprintf(stderr, "Error receiving data %d\n", WSAGetLastError());
}
printf("Received bytes %d\n Received string \"%s\"\n", bytecount, buffer);
char buff[1] = {0x11};
if((bytecount = send(*csock, buff, 1, 0))==SOCKET_ERROR){
fprintf(stderr, "Error sending data %d\n", WSAGetLastError());
}
printf("Sent bytes: %d. Send Message: %s\n ", bytecount,buff);
free(csock);
}
I suspect the issue not be the creating a thread, but in the passing of the data. It is probably simpler to just pass the socket to the thread. Additionally, at the end of the function you correctly free the memory, but you did not close the socket. I have made changes and verified that it functions correctly. The changes I made are comments with //*
#include <winsock2.h>
#include <windows.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
DWORD WINAPI SocketHandler(void*);
//*** Changed to work with my version of
//*** Visual Studio
int _tmain(int argc, _TCHAR* argv[]){
//The port you want the server to listen on
int host_port = 7878;
//Initialize socket support WINDOWS ONLY!
unsigned short wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 || ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2 )) {
fprintf(stderr, "Could not find useable sock dll %d\n",WSAGetLastError());
}
//Initialize sockets and set any options
//*** Changed to be SOCKET instead of int
SOCKET hsock;
int * p_int ;
hsock = socket(AF_INET, SOCK_STREAM, 0);
if(hsock == -1){
printf("Error initializing socket %d\n",WSAGetLastError());
}
p_int = (int*)malloc(sizeof(int));
*p_int = 1;
if( (setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char*)p_int, sizeof(int)) == -1 )||
(setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char*)p_int, sizeof(int)) == -1 ) ){
printf("Error setting options %d\n", WSAGetLastError());
free(p_int);
}
free(p_int);
//Bind and listen
struct sockaddr_in my_addr;
my_addr.sin_family = AF_INET ;
my_addr.sin_port = htons(host_port);
memset(&(my_addr.sin_zero), 0, 8);
my_addr.sin_addr.s_addr = INADDR_ANY ;
if( bind( hsock, (struct sockaddr*)&my_addr, sizeof(my_addr)) == -1 ){
fprintf(stderr,"Error binding to socket, make sure nothing else is listening on this port %d\n",WSAGetLastError());
}
if(listen( hsock, 10) == -1 ){
fprintf(stderr, "Error listening %d\n",WSAGetLastError());
}
//Now lets to the server stuff
//*** Changed to be SOCKET instead of int*
SOCKET csock;
sockaddr_in sadr;
int addr_size = sizeof(SOCKADDR);
while(true){
printf("waiting for a connection\n");
//*** Changed to comment out line as it is not needed
// csock = (SOCKET)malloc(sizeof(SOCKET));
//*** Changed check to be INVALID_SOCKET
if((csock = accept( hsock, (SOCKADDR*)&sadr, &addr_size))!= INVALID_SOCKET ){
printf("Received connection from %s",inet_ntoa(sadr.sin_addr));
//*** Changed to pass the client socket
CreateThread(0,0,&SocketHandler, (void*)csock , 0,0);
}
else{
fprintf(stderr, "Error accepting %d\n",WSAGetLastError());
}
}
}
DWORD WINAPI SocketHandler(void* lp){
//** Changed to cast as the SOCKET which was passed
SOCKET csock = (SOCKET)lp;
char buffer[1024];
int buffer_len = 1024;
int bytecount;
memset(buffer, 0, buffer_len);
if((bytecount = recv(csock, buffer, buffer_len, 0))==SOCKET_ERROR){
fprintf(stderr, "Error receiving data %d\n", WSAGetLastError());
}
printf("Received bytes: %d\nReceived string: \"%s\"\n", bytecount, buffer);
char buff[1] = {0x11};
if((bytecount = send(csock, buff, 1, 0))==SOCKET_ERROR){
fprintf(stderr, "Error sending data %d\n", WSAGetLastError());
}
printf("Sent bytes: %d. Send Message: %s\n ", bytecount,buff);
//*** Changed to close the socket after the message is sent. Otherwise
//*** the socket would remain open
closesocket(csock);
//*** Changed to comment the line out as there is
//*** no allocated memory.
//free(csock);
return 0;
}