How to manage a thread to receive/accept incoming connections and data receive, and other thread calls to SocketSendData and really send messages.
Actually some times messages are sended other times no....
Code:
/*
* SocketServer.c
*
* Created on: 5 de jul de 2018
* Author: sergiom
*/
#include <stdio.h>
#include <string.h> //strlen
#include <stdlib.h> //strlen
#include <sys/socket.h>
#include <arpa/inet.h> //inet_addr
#include <unistd.h> //write
#include <pthread.h> //for threading , link with lpthread
#include <netinet/in.h>
#include "CANSocket.h"
#include "SocketServer.h"
int qtdClientesConectados=0;
int arrClientesConectados[MAX_CLIENT_CONNECTED];
int StartSocketServer()
{
int socket_desc , client_sock , c;
struct sockaddr_in server , client;
struct in_addr ip_dest;
pthread_t thread_id;
pthread_t threadSend;
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Não foi possÃ..vel Criar o Socket!");
}
puts("Socket: Criado!");
ip_dest.s_addr = INADDR_ANY;
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr = ip_dest;
server.sin_port = htons( DEFAULT_PORT_LISTENER );
//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
//print the error message
perror("bind failed. Error");
return 1;
}
//Listen
listen(socket_desc , 3);
IniciarArrayConexao();
//Accept and incoming connection
puts("Socket: Aguardando conexões de entrada...");
c = sizeof(struct sockaddr_in);
while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) )
{
puts("Nova conexão aceita!");
if(pthread_create( &thread_id , NULL , ConnectionHandler , (void*) &client_sock) < 0)
{
perror("could not create thread");
return 1;
}
else
{
puts("SocketSendData");
SocketSendData("TESTEENVIO", 9);
}
//Now join the thread , so that we dont terminate before the thread
//pthread_join( thread_id , NULL);
}
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
return 0;
}
/*
* This will handle connection for each client
* */
void *ConnectionHandler(void *socket_desc)
{
//Get the socket descriptor
int sock = *(int*)socket_desc;
int readSize;
unsigned char *message , mensagemRecebida[TAM_BUFFER_RX_SOCKET];
puts ("Iniciou Thread ConnectionHandler");
AddClientToConnectedList(sock);
//SendHelloCANToSocket();
//Receive a message from client
while( (readSize = recv(sock , mensagemRecebida , TAM_BUFFER_RX_SOCKET , 0)) > 0 )
{
//end of string marker
WriteCAN(mensagemRecebida, readSize); // readSize);
//clear the message buffer
memset(mensagemRecebida, 0, TAM_BUFFER_RX_SOCKET);
}
if(readSize == 0)
{
puts("Cliente Desconectado");
fflush(stdout);
RemoveClientFromConnectedList(sock);
}
else if(readSize == -1)
{
perror("Falha ao Receber dados");
}
return 0;
}
void SocketSendData(unsigned char dataReadCAN[TAM_BUFFER_TX_SOCKET], int tamanho)
{
for(int cont=0; cont<MAX_CLIENT_CONNECTED; cont++)
{
if(arrClientesConectados[cont] != -1)
write(arrClientesConectados[cont] , dataReadCAN , tamanho);
}
return;
}
void IniciarArrayConexao()
{
for(int c=0; c<MAX_CLIENT_CONNECTED; c++)
arrClientesConectados[c] = -1;
}
void AddClientToConnectedList(int novaConexao)
{
if(qtdClientesConectados < MAX_CLIENT_CONNECTED)
{
for(int cont=0; cont<MAX_CLIENT_CONNECTED; cont++)
{
if(arrClientesConectados[cont] == -1)
{
AddToConnectedList(cont, novaConexao, NORMAL_ADD_OPERATION);
return;
}
}
puts("SocketServer: Não encontrou espaço para adicionar nova conexão!\n");
}
else
{
AddToConnectedList(MAX_CLIENT_CONNECTED - 1, novaConexao, FORCE_OVERWRITE);
printf("SocketServer: Quantidade de clientes conectados ultrapassa o número máximo permitido: %d - Última posição foi sobrescrita!\n", MAX_CLIENT_CONNECTED);
}
}
void AddToConnectedList(int posicao, int novaConexao, bool forceOverwrite)
{
arrClientesConectados[posicao] = novaConexao;
if(!forceOverwrite)
qtdClientesConectados++;
printf("SocketServer: Cliente adicionado a posição %d\n", posicao);
}
void RemoveClientFromConnectedList(int clienteDesconectado)
{
for(int cont=0; cont<MAX_CLIENT_CONNECTED; cont++)
{
if(arrClientesConectados[cont] == clienteDesconectado)
{
arrClientesConectados[cont] = -1;
printf("SocketServer: Cliente removido da posição %d\n", cont);
qtdClientesConectados--;
}
}
}