[4b15e0]: / SimpleSocketExample / main.c  Maximize  Restore  History

Download this file

109 lines (88 with data), 2.5 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
void printUsage();
typedef int bool;
#define true 1
#define false 0
int main( int argc, const char* argv[] )
{
/* ********************************************
* Actual socket code
**********************************************/
int socketfd; // socket handle
// open the socket
// http://man7.org/linux/man-pages/man2/socket.2.html
socketfd = socket(AF_INET, // IPv4
SOCK_STREAM, // a TCP connection
6); // protocol. 6 is TCP
if (!socketfd)
{
printf("opening socket failed\n");
return 1;
}
// no need to bind this one. CODESYS is already bound so it is acting as a server.
// We are a client, so we don't need a fixed address/port to be reached at
// connect to CODESYS
// first we need to create the struct where we put the connection info
struct sockaddr_in saCodesys;
// init the struct
bzero((char *) &saCodesys, sizeof(saCodesys));
// put in the information
saCodesys.sin_family = AF_INET; // IPv4
saCodesys.sin_port = htons(1200); // CODESYS port
// Convert IPv4 address from text to binary form
if(inet_pton(AF_INET, "127.0.0.1", (struct sockaddr *)&saCodesys.sin_addr)<=0)
{
printf("Invalid address/ Address not supported \n");
// close the socket
close(socketfd);
return 2;
}
if (connect(socketfd, (const struct sockaddr *)&saCodesys, sizeof(saCodesys)) < 0)
{
printf("Connection Failed %d\n", errno);
// close the socket
close(socketfd);
return 3;
}
/* *************************************
* Sending data
***************************************/
// super smart A.I. algorithm putting out production targets once a second
uint16_t uiProductionTarget = 0;
int counter = 0;
while (1)
{
uiProductionTarget = (sin(counter / 100.0) + 1) * 100;
if (send(socketfd, &uiProductionTarget, sizeof(uiProductionTarget), 0 /* no flags */) < 0)
{
printf("send failed. Ending.\n");
break;
}
else
{
printf("sent target: %d\n", uiProductionTarget);
}
sleep(1); // wait a ms before doing the math again.
counter ++;
}
// close the socket
close(socketfd);
printf("closing down.\n", );
return 0;
}
void printUsage()
{
printf("just run it\n");
}