Larus glider flight sensor system 3.9.2024
Software-In-The-Loop test and validation system
Loading...
Searching...
No Matches
TCP_server.cpp
Go to the documentation of this file.
1/***********************************************************************/
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29
30#ifndef _WIN32
31# include <unistd.h>
32# include <netdb.h>
33# include <netinet/in.h>
34# include <sys/socket.h>
35#else
36# include <winsock2.h>
37 typedef int socklen_t;
38# define close(x) closesocket(x) // in WinSock2.h the name of 'close' is 'closesocket'
39#endif
40#include <sys/types.h>
41#include "TCP_server.h"
42
45#ifdef _WIN32 // _MSC_VER
46# define sleep(x) Sleep(x)
47#endif
49
50 enum {MAX_CLIENTS=10};
53
55{
57 return false;
58
60 while( true)
61 {
63 if( client_descriptor > 0)
64 {
65 printf("New client accepted\n");
66#if _WIN32
67 u_long val = 1;
69#endif
70 break;
71 }
72 if( ! wait_for_client)
73 return false;
74 sleep(1);
75 }
76
79 return true;
80}
81
82bool open_TCP_port(void)
83{
84
85#ifdef _WIN32
86 static bool initialised = false;
87 if (!initialised) {
88 WSADATA data;
89 WSAStartup(MAKEWORD(2, 2), &data);
90 initialised = true;
91 }
92 const int type = SOCK_STREAM; // SOCK_NONBLOCK is not available on Windows!
93#else
94 const int type = SOCK_STREAM | SOCK_NONBLOCK;
95#endif // _WIN32
98 printf("Socket creation failed\n");
99 return false;
100 }
101
102 int opt = 0;
104 {
105 printf("Socket modification failed\n");
106 return false;
107 }
108#if _WIN32
109 u_long val = 1;
111#endif
112
113 memset(&servaddr, 0, sizeof(servaddr));
114
115 servaddr.sin_family = AF_INET;
116 servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
117 servaddr.sin_port = htons(TCP_PORT);
118
120 printf("Bind failed\n");
121 return false;
122 }
123
125 printf("Listen failed\n");
126 return false;
127 }
128 else
129 printf("Server listening\n");
130
131 len = sizeof(cli);
132 return true;
133}
134
135void write_TCP_port( char * data, unsigned length)
136{
137 accept_TCP_client(false);
138
139 int written_bytes;
140 unsigned remaining_length;
141 char * data_tail;
142
144 {
145 data_tail = data;
146 remaining_length = length;
147 do
148 {
149#ifdef _WIN32
151#else
153#endif
154 if( written_bytes < 0)
155 break;
156 // continue; // we have got some error and give up
159 }
160 while( remaining_length > 0);
161 }
162}
163
int TCP_clients[MAX_CLIENTS]
void close_TCP_port(void)
bool open_TCP_port(void)
bool accept_TCP_client(bool wait_for_client)
int number_of_TCP_clients
void write_TCP_port(char *data, unsigned length)
struct sockaddr_in servaddr cli
@ MAX_CLIENTS
int listening_socket_file_descriptor
socklen_t len
TCP server to feed XCsoar with flight data.
mathematical vector of arbitrary type and size
Definition vector.h:40
vector(void)
Definition vector.h:45
collection of system tuning parameters
#define TCP_PORT