/******************************************************************************
Online C Compiler.
Code, Compile, Run and Debug C program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h> //Header file for sleep(). man 3 sleep for details.
#include <pthread.h>
void main2(){
int valread=0;
char server_response[256];
char send_msg[256] = "Sending to server";
int server;
sleep(2);
server = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_port = htons(9002);
address.sin_addr.s_addr=INADDR_ANY;
printf("Client Socket successfully created..\n");
int con = connect(server,(struct sockaddr*) &address, sizeof(address));
if(con == -1) {
printf("Error with connection");
return ;
}
printf("connected to the server..\n");
int toServer = send(server, send_msg, sizeof(send_msg), 0);
if(toServer == -1) {
printf("Error with connection");
}
valread = recv(server, server_response, sizeof(server_response), 0);
printf(">>>%d \n", valread);
printf(">>>%s \n", server_response);
printf("end client\n");
return;
}
int main(){
int valread=0;
char server_response[256] = "Connected";
int server;
char from_client[256];
server = socket(AF_INET, SOCK_STREAM, 0);
if(server == -1) {
printf("Error with connection");
return -1;
}
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_port = htons(9002);
address.sin_addr.s_addr=INADDR_ANY;
int bindx = bind(server,(struct sockaddr*) &address, sizeof(address));
if(bindx == -1) {
printf("Error with connection");
return -1;
}
printf("Socket successfully binded..\n");
listen(server, 5);
printf("Server listening..\n");
//-------------------
pthread_t thread_id;
pthread_create(&thread_id, NULL, main2, NULL);
//---------------------
for(;;) {
int client_socket = accept(server, NULL, NULL);
if (client_socket < 0) {
printf("server accept failed...\n");
exit(0);
}
else
printf("server accept the client...\n");
valread = recv(client_socket, from_client, sizeof(from_client), 0);
printf("-->%d \n", valread);
printf("-->%s \n", from_client);
send(client_socket, server_response, sizeof(server_response), 0);
printf("again");
}
return 0;
}