Skip to content

Instantly share code, notes, and snippets.

@redatawfik
Last active June 13, 2020 03:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redatawfik/f3a8c1d93fd1314d3339bb1283d9d8a6 to your computer and use it in GitHub Desktop.
Save redatawfik/f3a8c1d93fd1314d3339bb1283d9d8a6 to your computer and use it in GitHub Desktop.
Client implementation of client-server chat using Winsock
#include <winsock2.h>
#include <iostream>
char szServerIPAddr[20] = "192.168.1.4"; // Put here the IP address of the server
int nServerPort = 5050; // The server port that will be used by // clients to talk with the server
bool InitWinSock2_0();
using namespace std;
int main() {
cout << "Enter the server IP Address: ";
cin >> szServerIPAddr;
cout << "Enter the server port number: ";
cin >> nServerPort;
if (!InitWinSock2_0()) {
cout << "Unable to Initialize Windows Socket environment" << WSAGetLastError() << endl;
return -1;
}
SOCKET hClientSocket;
hClientSocket = socket(
AF_INET, // The address family. AF_INET specifies TCP/IP
SOCK_STREAM, // Protocol type. SOCK_STREM specified TCP
0 // Protoco Name. Should be 0 for AF_INET address family
);
if (hClientSocket == INVALID_SOCKET) {
cout << "Unable to create Server socket" << endl;
// Cleanup the environment initialized by WSAStartup()
WSACleanup();
return -1;
}
// Create the structure describing various Server parameters
struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET; // The address family. MUST be AF_INET
serverAddr.sin_addr.s_addr = inet_addr(szServerIPAddr);
serverAddr.sin_port = htons(nServerPort);
// Connect to the server
if (connect(hClientSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0) {
cout << "Unable to connect to " << szServerIPAddr << " on port " << nServerPort << endl;
closesocket(hClientSocket);
WSACleanup();
return -1;
}
char szBuffer[1024] = "";
while (strcmp(szBuffer, "QUIT") != 0) {
cout << "Enter the string to send (QUIT) to stop: ";
cin >> szBuffer;
int nLength = strlen(szBuffer);
// send( ) may not be able to send the complete data in one go.
// So try sending the data in multiple requests
int nCntSend = 0;
char *pBuffer = szBuffer;
while ((nCntSend = send(hClientSocket, pBuffer, nLength, 0) != nLength)) {
if (nCntSend == -1) {
cout << "Error sending the data to server" << endl;
break;
}
if (nCntSend == nLength)
break;
pBuffer += nCntSend;
nLength -= nCntSend;
}
strupr(szBuffer);
if (strcmp(szBuffer, "QUIT") == 0) {
break;
}
nLength = recv(hClientSocket, szBuffer, sizeof(szBuffer), 0);
if (nLength > 0) {
szBuffer[nLength] = '\0';
cout << "Received " << szBuffer << " from server" << endl;
}
}
closesocket(hClientSocket);
WSACleanup();
return 0;
}
bool InitWinSock2_0() {
WSADATA wsaData;
WORD wVersion = MAKEWORD(2, 0);
if (!WSAStartup(wVersion, &wsaData))
return true;
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment