I have a multi-client chat server and for some reason only the first client is being added. I used a tutorial to help get me started. I have included my code below. When I try and add another client it doesnt appear to be added. If I add one client I get a response from the server like I want but only the first message I enter then after that it stops sending correctly.
Server Code:
int main(void)
{
struct sockaddr_in my_addr, cli_addr[10],cli_temp;
int sockfd;
socklen_t slen[10],slen_temp;
slen_temp = sizeof(cli_temp);
char buf[BUFLEN];
int clients = 0;
int client_port[10];
if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
{
printf("test\n");
err("socket");
}else{
printf("Server : Socket() successful\n");
}
bzero(&my_addr, sizeof(my_addr));
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(PORT);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sockfd, (struct sockaddr* ) &my_addr, sizeof(my_addr))==-1)
{
err("bind");
}else{
printf("Server : bind() successful\n");
}
int num_clients = 0;
while(1)
{
//receive
printf("Receiving...\n");
if (recvfrom(sockfd, buf, BUFLEN, 0, (struct sockaddr*)&cli_temp, &slen_temp)==-1)
err("recvfrom()");
if (clients <= 10) {
cli_addr[clients] = cli_temp;
client_port[clients] = ntohs(cli_addr[clients].sin_port);
clients++;
printf("Client added\n");
//printf("%d",clients);
int i;
for(i=0;sizeof(clients);i++) {
sendto(sockfd, buf, BUFLEN, 0, (struct sockaddr*)&cli_addr[i], sizeof(cli_addr[i]));
}
}
}
close(sockfd);
return 0;
}
I have included the client code as well in case it helps.
void err(char *s)
{
perror(s);
exit(1);
}
sig_atomic_t child_exit_status;
void clean_up_child_process (int signal_number)
{
/* Clean up the child process. */
int status;
wait (&status);
/* Store its exit status in a global variable. */
child_exit_status = status;
}
int main(int argc, char** argv)
{
struct sockaddr_in serv_addr;
int sockfd, slen=sizeof(serv_addr);
char buf[BUFLEN];
struct sigaction sigchld_action;
memset (&sigchld_action, 0, sizeof (sigchld_action));
sigchld_action.sa_handler = &clean_up_child_process;
sigaction (SIGCHLD, &sigchld_action, NULL);
int pid,ppid;
if(argc != 2)
{
printf("Usage : %s <Server-IP>\n",argv[0]);
exit(0);
}
if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
err("socket");
bzero(&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
if (inet_aton(argv[1], &serv_addr.sin_addr)==0)
{
fprintf(stderr, "inet_aton() failed\n");
exit(1);
}
pid = fork();
if (pid<0) {
err("Fork Error");
}else if (pid==0) {
//child process will receive from server
while (1) {
bzero(buf,BUFLEN);
//printf("Attempting to READ to socket %d: ",sockfd);
fflush(stdout);
//recvfrom here
if (recvfrom(sockfd, buf, BUFLEN, 0, (struct sockaddr*)&serv_addr, &slen)==-1)
err("recvfrom()");
printf("The message from the server is: %s \n",buf);
if (strcmp(buf,"bye\n") == 0) {
ppid = getppid();
kill(ppid, SIGUSR2);
break;
}
}
}else {
//parent will send to server
while(1){
printf("Please enter the message to send: ");
bzero(buf,BUFLEN);
fgets(buf,BUFLEN,stdin);
printf("Attempting to write to socket %d: ",sockfd);
fflush(stdout);
//send to here
if (sendto(sockfd, buf, BUFLEN, 0, (struct sockaddr*)&serv_addr, slen)==-1)
{
err("sendto()");
}
}
}
close(sockfd);
return 0;
}
Several problems jump out at me. First, every time you receive a message it will consider that to be a new client. Instead of just incrementing the clients variable for a message, you'll need to scan through the array to see if the source address is already present. Second, sizeof(clients) will return a static value (probably 4) depending on how many bytes an int occupies on your machine. That loop should be for( int i = 0; i < clients; i++ ).
You also have a variable named num_clients which is not used. Is that supposed to be there for something and maybe is causing some confusion?
Finally, instead of using the magic value 10 all over the place, use #define MAX_CONNECTIONS 10 and then replace all those numbers with MAX_CONNECTIONS. It's a lot easier to read and change later.
Related
I'm trying to implement an application using select(), but without closing the socket already served and without removing the corrispondent file descriptor from the main set of monitored socket (at least not immediatly). The goal is to create something similar to a set of "persistent connections".
The problem is that after I checked the ready socket, recv() continue to receive the last message a peer sent (running the code below, "Received" is printed infinited times). My thought is that the socket is still "ready", but I can't "mark" it as "unready" or "unchecked" to check it again only if there's a new message from that peer, and close it only in determinate conditions. How can I mark that socket as unready without close it? Is there another solution to implement persistent connections with select()?
Here it is a code of a simple application that I'm trying to program to understand how to realize persistent connections.
Server:
int main () {
int ret, sd, new_sd, len, i;
char buffer[1024];
fd_set master;
fd_set read_fds;
int fdmax;
struct sockaddr_in my_addr;
FD_ZERO(&master);
FD_ZERO(&read_fds);
sd = socket(AF_INET, SOCK_STREAM, 0);
memset(&my_addr, 0, sizeof(my_addr));
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(4257);
my_addr.sin_addr.s_addr = INADDR_ANY;
ret = bind(sd, (struct sockaddr*)&my_addr, sizeof(my_addr));
if(ret<0) {
perror("Error: ");
exit(1);
}
ret = listen(sd,10);
if(ret<0) {
perror("Error: ");
exit(-1);
}
FD_SET(sd, &master);
fdmax = sd;
for(;;) {
read_fds = master;
select(fdmax+1, &read_fds, NULL, NULL, NULL);
for(i=0; i<=fdmax; i++) {
if(FD_ISSET(i, &read_fds)) {
if(i == sd) {
len = sizeof(cl_addr);
new_sd = accept(sd, (struct sockaddr*)&cl_addr, &len);
FD_SET(new_sd, &master);
if(new_sd > fdmax)
fdmax = new_sd;
}
else {
ret = recv(i, buffer, 4, 0);
printf("Error: %s\n", strerror(errno));
printf("Received.\n");
if(strcmp(buffer, "DEL")==0) { /*Connection is closed only if client request it*/
close(i);
FD_CLR(i, &master);
printf("%d closed.\n",i);
continue;
}
len=strlen(buffer);
ret = send(i, (void*)buffer, len, 0);
if(ret<0) {
printf("socket n%d :\n",i);
perror("Error \n");
}
}
}
}
}
close(sd);
return 0;
}
I would be really grateful if you would help me, it is very important to me.
Edit: Client side is correct and send only once. "printf("Error: %s\n", strerror(errno));" print always "Success". After the first correct receiving, the program print infinite times these two printf after recv and buffer is empty.
Client:
int main (int argc, char* argv[]) {
int ret, sd, i, len;
char buffer[1024];
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(atoi(argv[1]));
inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr);
for(;;) {
scanf("%s",buffer);
if(strcmp(buffer,"c")==0) {
sd = socket(AF_INET, SOCK_STREAM, 0);
ret = connect(sd, (struct sockaddr*)&server_addr, sizeof(server_addr));
if(ret<0) {
perror("Error ");
exit(1);
}
}
if(strcmp(buffer, "REQ\0")==0) {
ret = send(sd, buffer, sizeof(buffer), 0);
if(ret<0) {
perror("Error ");
exit(1);
}
ret = recv(sd, (void*)buffer, 7, 0);
if(ret<0) {
perror("Error ");
exit(1);
}
printf("Received: %s\n", buffer);
}
if(strcmp(buffer, "DEL\0")==0) {
ret = send(sd, buffer, sizeof(buffer), 0);
if(ret<0) {
perror("Error ");
exit(1);
}
close(sd);
return 0;
}
}
}
I am new to socket programming, so I'm sorry if this is a noob question.
I have a program in C for Linux, which connects two sockets from "server.c" to two "client.c"s with the help of fork(). It works just fine most of the time, but there are times when the second client gets stuck before the first recv() function. On these occasions, the server doesn't accept() the connection and I am confused as to what is truly happening and how I can fix it.
Since I don't know much about socket programming, any explanation could be useful.
Here is the codes for the server and the client:
server.c
int main(){
int server_socket, p1_socket, p2_socket;
int pid;
pid = fork();
if(pid<0)
printf("Fork failed.\n");
else if(pid==0){
//PLAYER 1
socket_creation_and_connection(&server_socket, &p1_socket);
connect_to_player(&p1_socket, 1);
}
else{
//PLAYER 2
socket_creation_and_connection(&server_socket, &p2_socket);
connect_to_player(&p2_socket, 2);
}
printf("Hello message sent from %d\n", pid);
return 0;
}
void connect_to_player(int *socket, int playerNo){
char buffer[256];
while(1){
send(*socket , (int *)&playerNo , sizeof(int) , 0);
recv(*socket, (int *)&buffer, 1024, 0);
printf("PlayerNo %d Message received from client %s\n", playerNo, buffer);
}
}
void socket_creation_and_connection (int *server_socket, int *new_socket){
struct sockaddr_in address;
int addrlen = sizeof(address);
printf("creating sth\n");
if ((*server_socket = socket(AF_INET, SOCK_STREAM, 0)) == 0){
perror("Failed to create socket.");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
if (bind(*server_socket, (struct sockaddr *)&address, sizeof(address))<0){
perror("Failed to bind.");
exit(EXIT_FAILURE);
}
if (listen(*server_socket, 3)<0){
perror("Failed to listen.");
exit(EXIT_FAILURE);
}
if ((*new_socket = accept(*server_socket, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0){
perror("Failed to accept.");
exit(EXIT_FAILURE);
}
printf("finished creating sth\n");
}
client.c
int main(){
int client_socket = 0;
char message[256];
socket_creation_and_connection(&client_socket);
int intbuf;
while(1){
recv(client_socket, (int *)&intbuf, sizeof(int), 0);
if(intbuf == 1)
printf("Received message from Player1\n");
else
printf("Received message from Player2\n");
printf("Type a string\n");
scanf("%s", message);
send(client_socket, message , strlen(message) , 0 );
sleep(1);
}
return 0;
}
void socket_creation_and_connection(int *client_socket){
struct sockaddr_in address;
if ((*client_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_port = htons(PORT);
if (connect(*client_socket, (struct sockaddr *)&address, sizeof(address)) < 0)
{
printf("Connection Failed.\n");
exit(EXIT_FAILURE);
}
}
Edit: PORT is defined along with the libraries like this.
#define PORT 8080
I have created a server and client communication system in C and when the server is shutdown or quit, the client goes into an infinite loop repeating the last received message instead of quitting. I think the problem lies in recieveMessage function declaration but can't seem to pinpoint it.
How do I resolve this and how can I avoid this in the future?
#include"stdio.h"
#include"stdlib.h"
#include"sys/types.h"
#include"sys/socket.h"
#include"string.h"
#include"netinet/in.h"
#include"netdb.h"
#include"pthread.h"
#define PORT 4444
#define BUF_SIZE 2000
void * receiveMessage(void * socket) {
int sockfd, ret;
char buffer[BUF_SIZE];
sockfd = (int) socket;
memset(buffer, 0, BUF_SIZE);
for (;;) {
ret = recvfrom(sockfd, buffer, BUF_SIZE, 0, NULL, NULL);
if (ret < 0) {
printf("Error receiving data!\n");
break;
} else {
printf("server: ");
fputs(buffer, stdout);
//printf("\n");
}
}
}
int main(int argc, char**argv) {
struct sockaddr_in addr, cl_addr;
int sockfd, ret;
char buffer[BUF_SIZE];
char * serverAddr;
pthread_t rThread;
if (argc > 2) {
printf("usage: client < ip address >\n");
exit(1);
}
serverAddr = argv[1];
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
printf("Error creating socket!\n");
exit(1);
}
printf("Socket created...\n");
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("192.168.31.90");
addr.sin_port = PORT;
ret = connect(sockfd, (struct sockaddr *) &addr, sizeof(addr));
if (ret < 0) {
printf("Error connecting to the server!\n");
exit(1);
}
printf("Connected to the server...\n");
memset(buffer, 0, BUF_SIZE);
printf("Enter your messages one by one and press return key!\n");
//creating a new thread for receiving messages from the server
ret = pthread_create(&rThread, NULL, receiveMessage, (void *) sockfd);
if (ret) {
printf("ERROR: Return Code from pthread_create() is %d\n", ret);
exit(1);
}
while (fgets(buffer, BUF_SIZE, stdin) != NULL) {
ret = sendto(sockfd, buffer, BUF_SIZE, 0, (struct sockaddr *) &addr, sizeof(addr));
if (ret < 0) {
printf("Error sending data!\n\t-%s", buffer);
break;
}
puts(buffer);
}
close(sockfd);
pthread_exit(NULL);
return 0;
}
recvfrom returns zero when the other end of the connection is closed, not < 0.
Change your test of the return result as follows:
if (ret == 0)
{
printf("Connection closed!\n");
exit(0);
}
else if (ret < 0) {
printf("Error connecting to the server!\n");
exit(1);
}
I'm writing a chat room program that communicates over network using TCP. If user provide ip address as a command line argument, the program would attempt to connect to that address. If not, server will wait for others to connect.
The server has no problem receiving whatever text message the client send. However, the client side only receives text messages from server only when it sends its own message. How do I fix that so that client side receives messages right away? This is my code
Server code:
#define MAX_CLIENTS 100
static unsigned int cli_count = 0;
static int uid = 10;
typedef struct {
struct sockaddr_in addr;
int connfd;
int uid;
char name[32];
} client_t;
client_t *clients[MAX_CLIENTS];
void queue_add(client_t *cl)
{
int i;
for(i=0;i<MAX_CLIENTS;i++)
{
if(!clients[i])
{
clients[i] = cl;
return;
}
}
}
void queue_delete(int uid)
{
int i;
for(i=0;i<MAX_CLIENTS;i++)
{
if(clients[i])
{
if(clients[i]->uid == uid)
{
clients[i] = NULL;
return;
}
}
}
}
void send_message_all(char *s)
{
int i;
for(i=0;i<MAX_CLIENTS;i++)
{
if(clients[i])
{
write(clients[i]->connfd, s, strlen(s));
}
}
}
void *hanle_client(void *arg)
{
char buff_in[256];
char buff_out[256];
int rlen;
cli_count++;
client_t *cli = (client_t *)arg;
sprintf(buff_out, "<<JOIN, HELLO %s\r\n", cli->name);
send_message_all(buff_out);
bzero(buff_in,sizeof(buff_in));
while((rlen = read( cli->connfd,buff_in,sizeof(buff_in)-1))>0)
{
sprintf(buff_out, "[%s] %s\r\n", cli->name, buff_in);
send_message_all(buff_out);
}
close(cli->connfd);
/* Delete client from queue and yeild thread */
queue_delete(cli->uid);
free(cli);
cli_count--;
pthread_detach(pthread_self());
return NULL;
}
int main(int argc, char *argv[])
{
int listenfd = 0, connfd = 0, portno;
struct sockaddr_in serv_addr;
struct sockaddr_in cli_addr;
pthread_t tid;
if (argc < 2) {
printf("ERROR, no port provided\n");
exit(1);
}
//Create socket
listenfd= socket(AF_INET , SOCK_STREAM , 0);
if (listenfd == -1)
{
printf("Could not create socket");
}
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(portno);
/* Bind */
if(bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
{
perror("Socket binding failed");
return 1;
}
/* Listen */
if(listen(listenfd, 10) < 0)
{
perror("Socket listening failed");
return 1;
}
printf("<[SERVER STARTED]>\n");
socklen_t clilen = sizeof(cli_addr);
/* Accept clients */
while( (connfd = accept(listenfd, (struct sockaddr *)&cli_addr, (socklen_t*)&clilen)))
{
/* Client settings */
client_t *cli = (client_t *)malloc(sizeof(client_t));
cli->addr = cli_addr;
cli->connfd = connfd;
cli->uid = uid++;
sprintf(cli->name, "%d", cli->uid);
/* Add client to the queue and fork thread */
queue_add(cli);
pthread_create(&tid, NULL, &hanle_client, (void*)cli);
}
}
Client code:
int main(int argc , char *argv[])
{
int sockfd, portno ;
struct sockaddr_in serv_addr;
struct hostent *server;
char message[2000],server_reply[2000];
if (argc <3)
{
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(1);
}
portno = atoi(argv[2]);
//Create socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror("ERROR opening socket");
exit(1);
}
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(1);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(portno);
//Connect to remote server
if (connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
{
perror("ERROR connecting");
exit(1);
}
puts("Connected\n");
//keep communicating with server
while(1)
{
//Receive a reply from the server
bzero(server_reply,2000);
if( recv(sockfd , server_reply , 2000,0) < 0)
{
puts("recv failed");
break;
}
printf("%s", server_reply);
server_reply[0]='\0';
//Send Message to server
printf("Enter Message:");
bzero(message,2000);
fgets(message, sizeof(message),stdin);
if(send(sockfd , message , strlen(message),0) < 0)
{
puts("Send failed");
return 0;
}
}
close(sockfd);
return 0;
}
I am not sure if I understood your problem correctly. But at a high level, I noticed that your hanleClient method calls close(cli->connfd) on the clients socket after calling sendall. After calling close, you are deleting the client details from the queue. This way, the client being deleted will never receive any future messages. Are you sure this is what you want?
Try removing these lines and check if that is what you want -
close(cli->connfd);
/* Delete client from queue and yeild thread */
queue_delete(cli->uid);
free(cli);
cli_count--;
This way, whenever the server receives a message, it will try to send it to all clients that are connected to the server.
Note: Your code is not thread safe and will result in unexpected behaviour since you are accessing global data from within threads without using mutexes.
Here is a simple echo program using sockets and multi threads, it compiles and runs well in my Ubuntu if the client(via telnet) and server run on the same machine, but when I remotely connect to the server via telnet from another machine, it initially runs well(echos my message back every time), but some time later, there is no echo anymore even the telnet session is still alive, i am not sure where the problem is, can someone give some hits on this? I am new to multi thread programming and socket programming, learning on that.
#define ERROR -1
#define MAX_CLIENTS 2
#define MAX_DATA 1024
void* worker(void* sockId)
{
int socketId = *(int*)sockId;
int data_len = 1;
char data[MAX_DATA];
while(data_len > 0)
{
data_len = recv(socketId, data, MAX_DATA, 0);
if (data_len > 0)
{
send(socketId, data, data_len, 0);
data[data_len] = '\0';
printf("Sent message: %s", data);
}
}
printf("Client disconnected\n");
close(socketId);
}
int main(int argc, char* argv[])
{
if (argc <= 1)
{
printf("missing argument: port\n");
exit(-1);
}
struct sockaddr_in server;
struct sockaddr_in client;
int sock;
int new_connection;
int sockaddr_len = sizeof(struct sockaddr_in);
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == ERROR)
{
perror("server socket: ");
exit(-1);
}
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[1]));
server.sin_addr.s_addr = INADDR_ANY;
bzero(&server.sin_zero, 8);
if ((bind(sock, (struct sockaddr*)&server, sockaddr_len)) == ERROR)
{
perror("bind: ");
exit(-1);
}
if ((listen(sock, MAX_CLIENTS)) == ERROR)
{
perror("listen: ");
exit(-1);
}
while(1)
{
if ((new_connection = accept(sock, (struct sockaddr*)&client, &sockaddr_len)) == ERROR)
{
perror("accpet: ");
exit(-1);
}
printf("New Client connected from port: %d and IP: %s\n", ntohs(client.sin_port), inet_ntoa(client.sin_addr));
pthread_t thread;
pthread_create(&thread, NULL, worker, (void*)&new_connection);
pthread_detach(thread);
}
close(sock);
pthread_exit(NULL);
return 0;
}
Add some logging and you'll probably find that your code is blocked in send. You use naive, sequential I/O, so if the other end of the connection stops reading data, soon you do too.