// Client side C/C++ program to demonstrate Socket programming //this uses threads to allow a server and a client to do network chat stuff over 127.0.0.1:8080. the ui is out of sync because it doesn't use ncurses but the message sending and printing part still works #include #include #include #include #include #include #include #include #define PORT 8080 using namespace std; #ifdef _WIN32 /#include ; void fnsleep(unsigned milliseconds) { Sleep(milliseconds); } #else #include void fnsleep(unsigned milliseconds) { usleep(milliseconds * 1000); } #endif void checkForNewMsgs(int socket, int valreaded, int otherNum); void checkForNewMsgs(int socket, int valreaded, int otherNum) { int valreadOne; char newBuffer[1024] = {0}; while (3 == 3 && newBuffer != "exit") { for(int i = 0; i < 1024; i++) { newBuffer[i] = char(0); } valreadOne = read( socket , newBuffer, 1024); if (newBuffer != "") { cout << "Server: "; printf("%s\n",newBuffer ); } } fnsleep(1000); } int main(int argc, char const *argv[]) { int sock = 0, valread; struct sockaddr_in serv_addr; char *hello = "Hello from client"; char buffer[1024] = {0}; if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Socket creation error \n"); return -1; } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); // Convert IPv4 and IPv6 addresses from text to binary form if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0) { printf("\nInvalid address/ Address not supported \n"); return -1; } if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("\nConnection Failed \n"); return -1; } string message; thread t(checkForNewMsgs, sock, valread, 1024); t.detach(); while (message != "exit") { cout << "> "; getline(cin, message); send(sock , message.c_str() , strlen(message.c_str()) , 0 ); //printf("Hello message sent\n"); //valread = read( sock , buffer, 1024); //printf("%s\n",buffer ); } return 0; }