im writing a chat server in c and am need help.
my server can write to a socket, the client can read from the socket.
How do i have the client write to the socket and have the server read from
the client socket?
server.c
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
int main(){
int sockfd = socket(AF_INET,SOCK_STREAM,0);
if(sockfd < 0) return 1;
struct sockaddr_in server;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(2020);
server.sin_family = AF_INET;
if((bind(sockfd,(struct sockaddr *)&server,sizeof(server))) < 0 ){
printf("Bind Error\n");
return 1;
}
struct sockaddr_in client;
socklen_t clientsize = sizeof(client);
listen(sockfd,1);
int clientfd = accept(sockfd,(struct sockaddr *)&server,&clientsize);
if(accept < 0){
printf("Accept Error\n");
return 1;
}
char message[20];
printf("Enter a Line: ");
fgets(message,sizeof(message),stdin);
int c=0;
while(message[c++] != '\n'){
}
write(clientfd,message,c);
//want to read from client connection
close(sockfd);
close(clientfd);
return 0;
}
client.c
#include <stdio.h>
#include <netdb.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
int main(){
int sockfd = socket(AF_INET,SOCK_STREAM,0);
if(sockfd < 0) return 1;
struct sockaddr_in client;
client.sin_addr.s_addr = inet_addr("local");
client.sin_port = htons(2020);
client.sin_family = AF_INET;
int serverfd = connect(sockfd,(struct sockaddr *)&client,sizeof(client));
if(serverfd < 0){
printf("Connect Error\n");
return 1;
}
int b[2];
while(read(sockfd,b,1) > 0){
printf("%c",b[0]);
b[1] = '\0';
}
printf("\n");
char bu[2] = {'l','e'};
write(sockfd,b,2);
close(sockfd);
return 0;
}