TCP communication
Diff: TCP_COMM.cpp
- Revision:
- 0:6e800fc6935f
- Child:
- 1:174bf74eba86
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/TCP_COMM.cpp Sun Apr 03 15:44:37 2016 +0000 @@ -0,0 +1,101 @@ +#include "TCP_COMM.h" + +TCP_Communication::TCP_Communication() + :threadSocket(&TCP_Communication::threadReceiverStarter, this, osPriorityHigh,1024) +{ + threadSocket.signal_set(0x01); +} + +TCP_Communication::TCP_Communication(string _addr, int _port) + :threadSocket(&TCP_Communication::threadReceiverStarter, this, osPriorityHigh,1024) +{ + address = _addr.c_str(); + port = _port; + + threadSocket.signal_set(0x02); +} + +void TCP_Communication::threadServerStarter(const void *args) +{ + printf("Thread Server Starter \n"); + TCP_Communication *instance = (TCP_Communication*)args; + instance->threadServerWorker(); +} + +void TCP_Communication::threadReceiverStarter(void const *args) +{ + printf("Thread Receiver Starter \n"); + TCP_Communication *instance = (TCP_Communication*)args; + instance->threadReceiverWorker(); +} + +void TCP_Communication::threadServerWorker() +{ + threadSocket.signal_wait(0x01); + + TCPSocketServer server; + server.bind(SERVER_PORT); + server.listen(); + + while(1) + { + printf("Wait for new connection...\n"); + TCPSocketConnection client; + server.accept(client); + client.set_blocking(false, 1500); // Timeout after (1.5)s + + printf("Connection from: %s\n", client.get_address()); + char dataBuffer[256]; + while (true) { + int lengthData = client.receive(dataBuffer, sizeof(dataBuffer)); + if (lengthData <= 0) break; + + // print received message to terminal + dataBuffer[lengthData] = '\0'; + printf("Received message from Client :'%s'\n",dataBuffer); + } + client.close(); + } +} + +void TCP_Communication::threadReceiverWorker() +{ + threadSocket.signal_wait(0x02); + + while(1) + { + printf("Receiver Worker thread \n"); + char message[256]; + int messageLength; + messageLength = socket.receive(message, 256); + if(messageLength <= 0) + { + printf("This thread yield \n"); + Thread::yield(); + continue; + } + message[messageLength] = '\0'; // String end type + printf("Received message from server: '%s' %i \n", message, messageLength); + } + closeSocketConnection(); +} + +void TCP_Communication::initSocket() +{ + while (socket.connect(address, port) < 0) { + printf("Unable to connect to (%s) on port (%d)\n", address, port); + wait(1); + } + printf("Connected to Server at %s\n",address); +} + +void TCP_Communication::sendDataSocket(char *data) +{ + printf("Sending message data to Server : '%s' length %i \n",data, strlen(data)); + socket.send_all(data, strlen(data)); +} + +void TCP_Communication::closeSocketConnection() +{ + socket.close(); +} \ No newline at end of file