socket sever and client separate programs

+2 jonathan lee · February 2, 2016
Hey just wondering if any one could point me to some good examples of a sever and client programs that communicate over sockets. 

seen the MSDN one and that doesn't work for me for some reason. 

simpler the example the better. 

I am using visual studios 2015.

Cheers for all your help.

Post a Reply

Replies

Oldest  Newest  Rating
0 jonathan lee · February 26, 2016
bump
+1 Franz Schmidt · February 27, 2016
Yes server client programs already got me a while ago and also took me some time to figure it out.

The first thing is you need two programs:

  • Server program:
    The server waits for a incomming connectionrequest and recieves and sends messages

  • Client program:
    The client sends a connectionrequest to the server and can recieve and send messages a 



Serverprogram:
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
#include "string.h"
#include "windows.h"
#include <iostream>
using namespace std;

#include <errno.h>
#include <winsock.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library

int main(){
cout << "Hallo I'm a Server!" << endl << endl;

WSADATA wsaData;
if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) { //initiate use of the winsock DLL
fprintf(stderr, "WSAStartup(): Couldn't initialize Winsock.\n\n");
exit(EXIT_FAILURE);
}
else{
cout << "Winsock initialized!" << endl << endl;

int sock = socket(AF_INET, SOCK_STREAM, 0); //create socket which the server uses to listen for incomming connections via internet and socket stream
if (sock == -1) {
perror("socket()");
cout << "Creating socket failed!" << endl << endl;
}
else{
cout << "Socket created!" << endl << endl;

sockaddr_in my_addr;
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(5000); //this can be any number but make sure you don't use ports which are needed by other programs (e.g.: skype uses port 80)
my_addr.sin_addr.s_addr = htonl(INADDR_ANY); //my_addr gets the ip address of the computer where you execute this program
if (bind(sock, (sockaddr *)&my_addr, sizeof(sockaddr)) == -1) { //a port always needs to be bound to a socket
perror("bind()");
cout << "Binding port failed!" << endl << endl;
}else{
cout << "Port bound!" << endl;
int len;
getsockname(sock, (sockaddr *)&my_addr, &len); //get the socket a address to listen from
printf("Port: %d\n\n", ntohs(my_addr.sin_port));

if (listen(sock, 5) == -1) { // listen for incomming connection (the second parameter is the maximum length of the queue of pending connections)
perror("listen()");
cout << "Can't wait for clientconnections!" << endl << endl;
}else{
cout << "Waiting for clientconnections!" << endl << endl;

int sin_size = sizeof (sockaddr_in);
sockaddr_in remote_host;
int client_sock = accept(sock, (sockaddr *)&remote_host, &sin_size); //accept the request and create a communication socket for this client
if (client_sock == -1) {
perror("accept()");
cout << "Can't accept clientconnection!" << endl << endl;
}else{
cout << "Accepted clientconnection!" << endl << endl;

while (1){ // the rest from here is just communication and is completly independet. If you got this far you basicaly have working server-client-connection
_getch(); //wait to continue (press any key)

                                                       //send a message
char *msg = "Hallo I'm a Server!"; //define a message you want to send
int len = strlen(msg);
if (send(client_sock, msg, len, 0) == -1) { //send the message to the client via the created client socket
perror("send()");
cout << "Sending failed!" << endl << endl;
}
else{
cout << "Message sent: " << msg << endl << endl;

                                                               //recieve a message
char buf[1024]; //the length of the buffer for a message you want to recieve always needs to be predefined
memset(buf, '\0', sizeof(buf)); //clear the array from any useless signs
if (recv(client_sock, buf, 1024, 0) == -1) { //wait for a message from the client (this a very annoying thing this function actualy waits for a message infinitely)
perror("recv()");
cout << "Receiving failed!" << endl << endl;
}
else{
cout << "Message received:" << endl;
cout << buf << endl;
}
}
}
}
}
}
}
}
WSACleanup(); //close the winsock DLL
return 0;
}



Clientprogram:
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
#include "string.h"
#include "windows.h"
#include <iostream>
using namespace std;

#include <errno.h>
#include <winsock.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library

int main(){
cout << "Hallo I'm a Client!" << endl << endl;

WSADATA wsaData;
if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) { //initiate use of the winsock DLL
fprintf(stderr, "WSAStartup(): Couldn't initialize Winsock.\n\n");
exit(EXIT_FAILURE);
}
else{
cout << "Winsock initialized!" << endl << endl;

int sock = socket(AF_INET, SOCK_STREAM, 0); //create socket which the server uses to listen for incomming connections via internet and socket stream
if (sock == -1) {
perror("socket()");
cout << "Creating socket failed!" << endl << endl;
}
else{
cout << "Socket created!" << endl << endl;

char serv_addr_ip[] = "192.168.1.101"; //This needs to be the ip address of the pc where the server program was executed (that means you can run these programs on two different computers)
sockaddr_in serv_addr;
serv_addr.sin_family = AF_INET;
servent* serviceinfo = getservbyname("http", "tcp");
serv_addr.sin_port = serviceinfo->s_port;
               serv_addr.sin_port = htons(5000);
serv_addr.sin_addr.s_addr = inet_addr(serv_addr_ip); //till here the configuration of the address

if (connect(sock, (sockaddr *)&serv_addr, sizeof(sockaddr)) == -1) { //send a connection request to the server
perror("connect()");
cout << "Connection failed!" << endl << endl;
}
else{
cout << "Connected to " << serv_addr_ip << "!" << endl << endl;

while (1){ //again from here you have a working server-client-connection the rest is just to test the communication
_getch(); //wait for continue (press any key

                                       //send message
char *msg = "Hallo I'm a Client!"; //define a message you want to send
int len = strlen(msg);
if (send(sock, msg, len, 0) == -1) { //send the message to the server
perror("send()");
cout << "Sending failed!" << endl << endl;
}
else{
cout << "Message sent: " << msg << endl << endl;

                                               /recieve message
char buf[1024]; //again declair a buffer for your message
memset(buf, '\0', sizeof(buf)); //clear it
if (recv(sock, buf, 1024, 0) == -1) { //and wait for the incomming message (noticed something here: both wait for a message that means if you didn't send a message before the server would stay here at this point and your program would stuck)
perror("recv()");
cout << "Receiving failed!" << endl << endl;
}
else{
cout << "Message received:" << endl;
cout << buf << endl;
}
}
}
}
}
}
WSACleanup(); //again clear winsock dll
return 0;
}


These code are only a sample and can't really be used in a network since they only can make one connection at a time. I also made a little chat program which is still a little bugs, I could post it as well if you insist :)

The problem as I mentioned in the client program description is that the recieving of a message is a little bit hard to handle. I solved it with threads but I don't think it's the best solution for it. I created a communication thread and a connection thread, but I think this goes beyond the scope.

Hope this helps you and have fun with it :D
+1 Perverse Programmer · February 27, 2016
Have you considered using Boost.asio?
0 jonathan lee · February 28, 2016
cheers guys that has helped a lot
  • 1

C++

126,769 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator