Simple fix. Move the function definitions above the void father() function.
In code
sem_t mutex;
sem_t S;
char buffer[1024];
void error(const char *msg)
{
perror(msg);
exit(0);
}
/*
void signal_callback_handler()
{
close(sockfd);
}
*/
void takef(int &sockfd)
{
/*
*
* *Other code*
*
*
*/
testa(sockfd);
/* *Other code*
*
*
*/
}
void testa(int &sockfd)
{
/*
*
*
* *Other code*
*
*
*/
}
void putf(&sockfd)
{
/*
*
*
* *Other code*
*
*
*/
test();
test();
sem_post(&mutex);
}
void father(int &sockfd)
{
while(1)
{
srand(time(NULL));
int ms = rand() % 2000 + 5000
send(sockfd, DATA, strlen(DATA), 0);
usleep(1000*ms);
takef(sockfd);
putf(sockfd);
}
}
int main(int argc, char *argv[])
{
/*
*
*
* *Other code*
*
*
*/
father(sockfd);
return 0;
}
Or another alternative, like mentioned below, is to write a function prototype. This is similar to how one would write a prototype for functions in a header file and then define the functions in a .cpp file. A function prototype is a function without a body and lets the compiler know the function exists but is not defined yet.
Here is an example using prototyping
sem_t mutex;
sem_t S;
char buffer[1024];
void error(const char *msg)
{
perror(msg);
exit(0);
}
/*
void signal_callback_handler()
{
close(sockfd);
}
*/
// Prototypes
void takef(int &sockfd);
void testa(int &sockfd);
void putf(&sockfd);
void father(int &sockfd)
{
while(1)
{
srand(time(NULL));
int ms = rand() % 2000 + 5000
send(sockfd, DATA, strlen(DATA), 0);
usleep(1000*ms);
takef(sockfd);
putf(sockfd);
}
}
void takef(int &sockfd)
{
/*
*
* *Other code*
*
*
*/
testa(sockfd);
/* *Other code*
*
*
*/
}
void testa(int &sockfd)
{
/*
*
*
* *Other code*
*
*
*/
}
void putf(&sockfd)
{
/*
*
*
* *Other code*
*
*
*/
test();
test();
sem_post(&mutex);
}
int main(int argc, char *argv[])
{
/*
*
*
* *Other code*
*
*
*/
father(sockfd);
return 0;
}
SergeyKagen 3 / 4 / 2 Регистрация: 02.04.2018 Сообщений: 315 |
||||
1 |
||||
19.04.2019, 22:16. Показов 131576. Ответов 14 Метки нет (Все метки)
Простой код, но Arduino IDE напрочь отказывается принимать переменные. Что за глюк или я что-то неправильно делаю?
ошибка при компиляции «‘count’ was not declared in this scope», что не так?
__________________
0 |
marat_miaki 495 / 389 / 186 Регистрация: 08.04.2013 Сообщений: 1,688 |
||||
19.04.2019, 23:26 |
2 |
|||
Решение
1 |
Lavad 0 / 0 / 0 Регистрация: 03.10.2015 Сообщений: 25 |
||||||||
14.09.2019, 22:33 |
3 |
|||||||
Доброго времени суток!
В loop() делаю вызов:
При компиляции выделяется этот вызов, с сообщением: ‘myDisplay’ was not declared in this scope Замучился искать инфу о декларации/обьявлении функции. Везде, что находил, понимал одно: если ты вызываешь функцию, это и есть обьявление функции P.S. Код, что использовал в качестве функции, работоспособен. Раньше находился в loop(). Скетч постепенно разрастается, много однотипных обращений к дисплею…
0 |
8385 / 6147 / 615 Регистрация: 10.12.2010 Сообщений: 28,683 Записей в блоге: 30 |
|
14.09.2019, 23:57 |
4 |
Создал функцию (за пределами setup и loop), Перевидите на нормальный язык. В другом файле что ли? Добавлено через 1 минуту
Замучился искать инфу о декларации/обьявлении функции. Везде, что находил, понимал одно: если ты вызываешь функцию, это и есть обьявление функции Читать учебники по С++ не пробовали? https://metanit.com/cpp/tutorial/3.1.php Специфика Arduino лишь отличается тем что пред объявления не всегда нужны. Добавлено через 7 минут
0 |
ValeryS Модератор 8759 / 6549 / 887 Регистрация: 14.02.2011 Сообщений: 22,972 |
||||
15.09.2019, 00:09 |
5 |
|||
Везде, что находил, понимал одно: если ты вызываешь функцию, это и есть обьявление функции это где ж такое написано?
а объявить уже в удобном месте
0 |
0 / 0 / 0 Регистрация: 03.10.2015 Сообщений: 25 |
|
15.09.2019, 00:48 |
6 |
Неделю назад ВПЕРВЫЕ включил Arduino Uno. Написал на том же языке, что и читал на всяких форумах и справочниках по Arduino :-). За пределами этих функций — значит не внутри них. Обе приведенных Вами ссылок просмотрел, проверил в скетче… В итоге вылезла другая ошибка: void myDisplay(byte x, byte y, char str) тоже пробовал. Та же ошибка. Что не так на этот раз?
0 |
Модератор 8759 / 6549 / 887 Регистрация: 14.02.2011 Сообщений: 22,972 |
|
15.09.2019, 01:26 |
7 |
В итоге вылезла другая ошибка: точку с запятой в конце поставил?
1 |
Lavad 0 / 0 / 0 Регистрация: 03.10.2015 Сообщений: 25 |
||||||||||||
15.09.2019, 08:46 |
8 |
|||||||||||
Вот скетч. Проще некуда.
Любое из трех так называемых «объявлений» (строки 7…9) выдает одну и ту же ошибку — я пытаюсь объявить функцию как переменную. Добавлено через 9 минут
Компилятор задумался (я успел обрадоваться), но, зараза :-), он снова поставил свой автограф undefined reference to `myDisplay(unsigned char, unsigned char, char, float) На этот раз он пожаловался на строку вызова функции. Добавлено через 34 минуты
Dispay вместо Display Добавлено через 8 минут
0 |
ValeryS Модератор 8759 / 6549 / 887 Регистрация: 14.02.2011 Сообщений: 22,972 |
||||||||
15.09.2019, 10:36 |
9 |
|||||||
void myDisplay(byte, byte, char, float) = 0; вот так не надо делать(приравнивать функцию к нулю) Добавлено через 5 минут
void myDispay(byte x, byte y, char str, float temp)
myDisplay(0, 0, «C», temp); просишь чтобы функция принимала символ
или проси передавать строку, например так
1 |
Avazart 8385 / 6147 / 615 Регистрация: 10.12.2010 Сообщений: 28,683 Записей в блоге: 30 |
||||
15.09.2019, 12:02 |
10 |
|||
Кроме того наверное лучше так:
Тогда можно будет вынести ф-цию в отдельный файл/модуль.
1 |
locm |
15.09.2019, 21:07
|
Не по теме:
Arduino Uno.
AVR (Basic, немного Assembler). Arduino Uno это AVR, для которого можете писать на бейсике или ассемблере.
0 |
Avazart |
15.09.2019, 21:21
|
Не по теме:
Arduino Uno это AVR, для которого можете писать на бейсике или ассемблере. Но лучше не надо …
0 |
Lavad 0 / 0 / 0 Регистрация: 03.10.2015 Сообщений: 25 |
||||
16.09.2019, 12:12 |
13 |
|||
это где ж такое написано? Оказалось, что я верно понял чтиво по справочникам:
вот так не надо делать(приравнивать функцию к нулю)… Методом проб и ошибок уже понял :-).
или передавай символ… Если передаю в одинарных кавычках более одного символа, а функция ждет как
или проси передавать строку, например так… Буквально вчера попалось это в справочнике, но как-то не дошло, что тоже мой вариант :-).
Кроме того наверное лучше так:
Тогда можно будет вынести ф-цию в отдельный файл/модуль. Благодарю за совет! Как-нибудь проверю…
0 |
8385 / 6147 / 615 Регистрация: 10.12.2010 Сообщений: 28,683 Записей в блоге: 30 |
|
16.09.2019, 12:54 |
14 |
Оказалось, что я верно понял чтиво по справочникам: если ты вызываешь функцию, это и есть обьявление функции Нафиг выкиньте эти справочники.
0 |
0 / 0 / 0 Регистрация: 03.10.2015 Сообщений: 25 |
|
16.09.2019, 13:00 |
15 |
Ссылки Ваши добавлены в закладки. Время от времени заглядываю.
0 |
Ok, so I tried the very latest release and I don’t even know where to start with that….
How the hell does a new release go from one or two errors to this shower of sh*t?
Command:570: error: variable or field ‘printDirectory’ declared void
void printDirectory(File dir, int numTabs) {
^
Command:570: error: ‘File’ was not declared in this scope
Command:570: error: expected primary-expression before ‘int’
void printDirectory(File dir, int numTabs) {
^
Networking:414: error: variable or field ‘SSDP_schema’ declared void
void SSDP_schema(WiFiClient &client) {
^
Networking:414: error: ‘WiFiClient’ was not declared in this scope
Networking:414: error: ‘client’ was not declared in this scope
void SSDP_schema(WiFiClient &client) {
^
_N001_Email:113: error: ‘WiFiClient’ was not declared in this scope
boolean NPlugin_001_MTA(WiFiClient& client, String aStr, const String &aWaitForPattern)
^
_N001_Email:113: error: ‘client’ was not declared in this scope
boolean NPlugin_001_MTA(WiFiClient& client, String aStr, const String &aWaitForPattern)
^
_N001_Email:113: error: expected primary-expression before ‘aStr’
boolean NPlugin_001_MTA(WiFiClient& client, String aStr, const String &aWaitForPattern)
^
_N001_Email:113: error: expected primary-expression before ‘const’
boolean NPlugin_001_MTA(WiFiClient& client, String aStr, const String &aWaitForPattern)
^
_N001_Email:113: error: expression list treated as compound expression in initializer [-fpermissive]
boolean NPlugin_001_MTA(WiFiClient& client, String aStr, const String &aWaitForPattern)
^
C:ProjectssonoffESPeasyFW2SourceESPeasyCommand.ino: In function ‘bool safeReadStringUntil(Stream&, String&, char, unsigned int, unsigned int)’:
Command:28: error: ‘LOG_LEVEL_ERROR’ was not declared in this scope
addLog(LOG_LEVEL_ERROR, F(«Not enough bufferspace to read all input data!»));
^
Command:36: error: ‘LOG_LEVEL_ERROR’ was not declared in this scope
addLog(LOG_LEVEL_ERROR, F(«Timeout while reading input data!»));
^
C:ProjectssonoffESPeasyFW2SourceESPeasyCommand.ino: In function ‘void ExecuteCommand(byte, const char*)’:
Command error: ‘Settings’ was not declared in this scope
if (Settings.NotificationEnabled[Par1 — 1] && Settings.Notification[Par1 — 1] != 0)
^
Command:103: error: ‘NPLUGIN_NOT_FOUND’ was not declared in this scope
if (NotificationProtocolIndex!=NPLUGIN_NOT_FOUND)
^
Command:105: error: aggregate ‘EventStruct TempEvent’ has incomplete type and cannot be defined
struct EventStruct TempEvent;
^
Command:108: error: ‘NPlugin_ptr’ was not declared in this scope
NPlugin_ptr[NotificationProtocolIndex](NPLUGIN_NOTIFY, &TempEvent, message);
^
Command:108: error: ‘NPLUGIN_NOTIFY’ was not declared in this scope
NPlugin_ptr[NotificationProtocolIndex](NPLUGIN_NOTIFY, &TempEvent, message);
^
Command:117: error: ‘RTC’ was not declared in this scope
RTC.flashDayCounter = 0;
^
Command:134: error: ‘File’ was not declared in this scope
File root = SD.open(«/»);
^
Command:134: error: expected ‘;’ before ‘root’
File root = SD.open(«/»);
^
Command:135: error: ‘root’ was not declared in this scope
root.rewindDirectory();
^
Command:136: error: ‘printDirectory’ was not declared in this scope
printDirectory(root, 0);
^
Command:147: error: ‘SD’ was not declared in this scope
SD.remove((char*)fname.c_str());
^
Command:152: error: ‘lowestRAM’ was not declared in this scope
Serial.print(lowestRAM);
^
Command:154: error: ‘lowestRAMfunction’ was not declared in this scope
Serial.println(lowestRAMfunction);
^
Command:167: error: ‘loopCounterLast’ was not declared in this scope
Serial.print(100 — (100 * loopCounterLast / loopCounterMax));
^
Command:167: error: ‘loopCounterMax’ was not declared in this scope
Serial.print(100 — (100 * loopCounterLast / loopCounterMax));
^
Command:185: error: ‘SecuritySettings’ was not declared in this scope
Serial.println(sizeof(SecuritySettings));
^
Command:187: error: ‘Settings’ was not declared in this scope
Serial.println(sizeof(Settings));
^
Command:189: error: ‘ExtraTaskSettings’ was not declared in this scope
Serial.println(sizeof(ExtraTaskSettings));
^
Command:191: error: ‘Device’ was not declared in this scope
Serial.println(sizeof(Device));
^
Command:203: error: ‘Wire’ was not declared in this scope
Wire.beginTransmission(Par1); // address
^
Command:212: error: ‘Wire’ was not declared in this scope
Wire.beginTransmission(Par1); // address
^
Command:228: error: ‘Settings’ was not declared in this scope
Settings.Build = Par1;
^
Command:235: error: ‘Settings’ was not declared in this scope
Settings.deepSleep = 0;
^
Command:245: error: ‘Wire’ was not declared in this scope
Wire.beginTransmission(address);
^
Command:267: error: aggregate ‘EventStruct TempEvent’ has incomplete type and cannot be defined
struct EventStruct TempEvent;
^
Command:286: error: ‘UserVar’ was not declared in this scope
UserVar[(VARS_PER_TASK * (Par1 — 1)) + Par2 — 1] = result;
^
Command:286: error: ‘VARS_PER_TASK’ was not declared in this scope
UserVar[(VARS_PER_TASK * (Par1 — 1)) + Par2 — 1] = result;
^
Command:298: error: ‘RULES_TIMER_MAX’ was not declared in this scope
if (Par1>=1 && Par1<=RULES_TIMER_MAX)
^
Command:303: error: ‘RulesTimer’ was not declared in this scope
RulesTimer[Par1 — 1] = millis() + (1000 * Par2);
^
Command:306: error: ‘RulesTimer’ was not declared in this scope
RulesTimer[Par1 — 1] = 0L;
^
Command:310: error: ‘LOG_LEVEL_ERROR’ was not declared in this scope
addLog(LOG_LEVEL_ERROR, F(«TIMER: invalid timer number»));
^
Command:324: error: ‘Settings’ was not declared in this scope
Settings.UseRules = true;
^
Command:326: error: ‘Settings’ was not declared in this scope
Settings.UseRules = false;
^
Command:335: error: ‘Settings’ was not declared in this scope
if (Settings.UseRules)
^
Command:351: error: ‘WiFi’ was not declared in this scope
if (strcasecmp_P(Command, PSTR(«Publish»)) == 0 && WiFi.status() == WL_CONNECTED)
^
Command:351: error: ‘WL_CONNECTED’ was not declared in this scope
if (strcasecmp_P(Command, PSTR(«Publish»)) == 0 && WiFi.status() == WL_CONNECTED)
^
Command:361: error: ‘MQTTclient’ was not declared in this scope
MQTTclient.publish(topic.c_str(), value.c_str(), Settings.MQTTRetainFlag);
^
Command:361: error: ‘Settings’ was not declared in this scope
MQTTclient.publish(topic.c_str(), value.c_str(), Settings.MQTTRetainFlag);
^
Command:365: error: ‘WiFi’ was not declared in this scope
if (strcasecmp_P(Command, PSTR(«SendToUDP»)) == 0 && WiFi.status() == WL_CONNECTED)
^
Command:365: error: ‘WL_CONNECTED’ was not declared in this scope
if (strcasecmp_P(Command, PSTR(«SendToUDP»)) == 0 && WiFi.status() == WL_CONNECTED)
^
Command:375: error: ‘IPAddress’ was not declared in this scope
IPAddress UDP_IP(ipaddress[0], ipaddress[1], ipaddress[2], ipaddress[3]);
^
Command:375: error: expected ‘;’ before ‘UDP_IP’
IPAddress UDP_IP(ipaddress[0], ipaddress[1], ipaddress[2], ipaddress[3]);
^
Command:376: error: ‘portUDP’ was not declared in this scope
portUDP.beginPacket(UDP_IP, port.toInt());
^
Command:376: error: ‘UDP_IP’ was not declared in this scope
portUDP.beginPacket(UDP_IP, port.toInt());
^
Command:381: error: ‘WiFi’ was not declared in this scope
if (strcasecmp_P(Command, PSTR(«SendToHTTP»)) == 0 && WiFi.status() == WL_CONNECTED)
^
Command:381: error: ‘WL_CONNECTED’ was not declared in this scope
if (strcasecmp_P(Command, PSTR(«SendToHTTP»)) == 0 && WiFi.status() == WL_CONNECTED)
^
Command:389: error: ‘WiFiClient’ was not declared in this scope
WiFiClient client;
^
Command:389: error: expected ‘;’ before ‘client’
WiFiClient client;
^
Command:390: error: ‘client’ was not declared in this scope
if (client.connect(host.c_str(), port.toInt()))
^
Command:407: error: ‘LOG_LEVEL_DEBUG’ was not declared in this scope
addLog(LOG_LEVEL_DEBUG, line);
^
Command:422: error: ‘SecuritySettings’ was not declared in this scope
strcpy(SecuritySettings.WifiSSID, Line + 9);
^
Command:428: error: ‘SecuritySettings’ was not declared in this scope
strcpy(SecuritySettings.WifiKey, Line + 8);
^
Command:434: error: ‘SecuritySettings’ was not declared in this scope
strcpy(SecuritySettings.WifiSSID2, Line + 10);
^
Command:440: error: ‘SecuritySettings’ was not declared in this scope
strcpy(SecuritySettings.WifiKey2, Line + 9);
^
Command:470: error: ‘Settings’ was not declared in this scope
Settings.Unit=Par1;
^
Command:476: error: ‘Settings’ was not declared in this scope
strcpy(Settings.Name, Line + 5);
^
Command:482: error: ‘SecuritySettings’ was not declared in this scope
strcpy(SecuritySettings.Password, Line + 9);
^
Command:503: error: ‘WiFi’ was not declared in this scope
WiFi.persistent(true); // use SDK storage of SSID/WPA parameters
^
Command:529: error: ‘Settings’ was not declared in this scope
Settings.SerialLogLevel = Par1;
^
Command:536: error: ‘Settings’ was not declared in this scope
if (!str2ip(TmpStr1, Settings.IP))
^
Command:547: error: ‘IPAddress’ was not declared in this scope
IPAddress ip = WiFi.localIP();
^
Command:547: error: expected ‘;’ before ‘ip’
IPAddress ip = WiFi.localIP();
^
Command:548: error: ‘ip’ was not declared in this scope
sprintf_P(str, PSTR(«%u.%u.%u.%u»), ip[0], ip[1], ip[2], ip[3]);
^
Command:550: error: ‘BUILD’ was not declared in this scope
Serial.print(F(» Build : «)); Serial.println((int)BUILD);
^
Command:551: error: ‘Settings’ was not declared in this scope
Serial.print(F(» Name : «)); Serial.println(Settings.Name);
^
Command:553: error: ‘SecuritySettings’ was not declared in this scope
Serial.print(F(» WifiSSID : «)); Serial.println(SecuritySettings.WifiSSID);
^
C:ProjectssonoffESPeasyFW2SourceESPeasyCommand.ino: At global scope:
Command:570: error: variable or field ‘printDirectory’ declared void
void printDirectory(File dir, int numTabs) {
^
Command:570: error: ‘File’ was not declared in this scope
Command:570: error: expected primary-expression before ‘int’
void printDirectory(File dir, int numTabs) {
^
ESPEasy:4: error: expected declaration before end of line
#pragma GCC diagnostic warning «-Wall»
Pages 1
You must login or register to post a reply
1 2020-02-24 09:38:10 (edited by KissInno 2020-02-24 09:50:37)
- KissInno
- Member
- Offline
- Registered: 2019-06-15
- Posts: 23
Topic: Lib 2.4.3 (14.11.2019) with PlatformIO VS Code
Sorry to bother again & again with this VSC topic but I must miss something with that new official lib. Is there anybody who was able to compile a very simple ESP32 project with Wifi connection?
I really need the latest Lib 2.4.3 to get this new Online Graph feature: https://remotexy.com/en/help/controls/onlinegraph/
I tried both download from https://github.com/RemoteXY/RemoteXY-Arduino-library or from https://remotexy.com/download/library/2 … moteXY.zip
For a strange reason, I’m back with compilation errors with VSC when using ESP32 Wifi. Exactly same (very simple) ESP32 WIFI project works perfectly under Arduino IDE but does not compile with VSC (while VSC has no issue with ESP32 BLE project).
Here are the VSC errors:
espcore_wifi.h libRemoteXYsrcmodules
‘class WiFiClass’ has no member named ‘softAPdisconnect’
‘class WiFiClass’ has no member named ‘mode’
‘WIFI_AP’ was not declared in this scope
‘class WiFiClass’ has no member named ‘softAP’
invalid new-expression of abstract class type ‘WiFiServer’
‘class WiFiServer’ has no member named ‘setNoDelay’
control reaches end of non-void function [-Wreturn-type]
or again 1st error shown in TERMINAL: libRemoteXYsrc/modules/espcore_wifi.h:42:10: error: ‘class WiFiClass’ has no member named ‘softAPdisconnect’
However, I do have the same lib’s in VSC as for Arduino IDE:
1) d:My_ProjectsESP32_RemoteXYlibRemoteXY
2) WiFi ver1.2.7 by Arduino installed as Global Lib
Here is my very simple test project for reference:
#include <Arduino.h>
/*
— ESP32_WIFI_AP —
This source code of graphical user interface
has been generated automatically by RemoteXY editor.
To compile this code using RemoteXY library 2.4.3 or later version
download by link http://remotexy.com/en/library/
To connect using RemoteXY mobile app by link http://remotexy.com/en/download/
— for ANDROID 4.5.1 or later version;
— for iOS 1.4.1 or later version;
This source code is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
*/
//////////////////////////////////////////////
// RemoteXY include library //
//////////////////////////////////////////////
// RemoteXY select connection mode and include library
#define REMOTEXY_MODE__ESP32CORE_WIFI_POINT // Remotexy is an Access Point to connect to
#include <WiFi.h>
#include <RemoteXY.h>
// RemoteXY connection settings
#define REMOTEXY_WIFI_SSID «Kiss Innovation 1»
#define REMOTEXY_WIFI_PASSWORD «12345678»
#define REMOTEXY_SERVER_PORT 6377
// RemoteXY configurate
#pragma pack(push, 1)
uint8_t RemoteXY_CONF[] =
{ 255,1,0,0,0,13,0,10,13,0,
1,0,38,15,26,26,2,31,88,0 };
// this structure defines all the variables and events of your control interface
struct {
// input variables
uint8_t button_1; // =1 if button pressed, else =0
// other variable
uint8_t connect_flag; // =1 if wire connected, else =0
} RemoteXY;
#pragma pack(pop)
/////////////////////////////////////////////
// END RemoteXY include //
/////////////////////////////////////////////
#define PIN_BUTTON_1 2
void setup()
{
RemoteXY_Init ();
pinMode (PIN_BUTTON_1, OUTPUT);
// TODO you setup code
}
void loop()
{
RemoteXY_Handler ();
digitalWrite(PIN_BUTTON_1, (RemoteXY.button_1==0)?LOW:HIGH);
// TODO you loop code
// use the RemoteXY structure for data transfer
}
My platformio.ini:
;PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:esp32doit-devkit-v1]
platform = espressif32
board = esp32doit-devkit-v1
framework = arduino
2 Reply by Guillaume 2020-02-24 15:08:06
- Guillaume
- Moderator
- Offline
- Registered: 2016-12-23
- Posts: 340
Re: Lib 2.4.3 (14.11.2019) with PlatformIO VS Code
Your example compiled without error for me so I don’t know what you are doing wrong
The only error I had was «cannot find RemoteXY.h» so the only change I made to your example was adding this line in platformio.ini : lib_extra_dirs = D:Arduinolibraries , path where I have a local copy of original remotexy library 2.4.3, but I could have added lib_deps = https://github.com/RemoteXY/RemoteXY-Arduino-library , it would work too
3 Reply by KissInno 2020-02-24 17:24:40 (edited by KissInno 2020-02-24 17:28:51)
- KissInno
- Member
- Offline
- Registered: 2019-06-15
- Posts: 23
Re: Lib 2.4.3 (14.11.2019) with PlatformIO VS Code
Thanks a lot Guillaume for your support!!! This is really crazy. I don’t understand what’s going wrong with my laptop Win10-Pro.
I’m running VSC 1.42.1 and I did Updates/Update All.
I tried to delete my old folder and make a new project, with Remotexy folder under project_namelib
I also tried with lib_deps = https://github.com/RemoteXY/RemoteXY-Arduino-library with project_namelib empty
I always see the same mistakes, like here in TERMINAL:
Executing task in folder toto1: C:Userschphnoi.platformiopenvScriptsplatformio.exe run —target upload <
Processing esp32doit-devkit-v1 (platform: espressif32; board: esp32doit-devkit-v1; framework: arduino)
————————————————————————————————————————-
Verbose mode can be enabled via `-v, —verbose` option
CONFIGURATION: https://docs.platformio.org/page/boards … it-v1.html
PLATFORM: Espressif 32 1.11.2 > DOIT ESP32 DEVKIT V1
HARDWARE: ESP32 240MHz, 320KB RAM, 4MB Flash
DEBUG: Current (esp-prog) External (esp-prog, iot-bus-jtag, jlink, minimodule, olimex-arm-usb-ocd, olimex-arm-usb-ocd-h,
olimex-arm-usb-tiny-h, olimex-jtag-tiny, tumpa) would work too
PACKAGES:
— framework-arduinoespressif32 3.10004.200129 (1.0.4)
— tool-esptoolpy 1.20600.0 (2.6.0)
— tool-mkspiffs 2.230.0 (2.30)
— toolchain-xtensa32 2.50200.80 (5.2.0)
LDF: Library Dependency Finder -> http://bit.ly/configure-pio-ldf
LDF Modes: Finder ~ chain, Compatibility ~ soft
Found 39 compatible libraries
Scanning dependencies…
Dependency Graph
|— <RemoteXY> 2.4.3
| |— <ESP32 BLE Arduino> 1.0.1
|— <WiFiEspAT> 1.1.1
Building in release mode
Compiling .piobuildesp32doit-devkit-v1srcWiFiPoint_ESP32.cpp.o
Compiling .piobuildesp32doit-devkit-v1libae2BLEBLECharacteristic.cpp.o
Compiling .piobuildesp32doit-devkit-v1libae2BLEBLECharacteristicMap.cpp.o
Compiling .piobuildesp32doit-devkit-v1libae2BLEBLEClient.cpp.o
In file included from D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h:9:0,
from D:ABCArduino_LibRemoteXYsrc/RemoteXY.h:170,
from srcWiFiPoint_ESP32.cpp:27:
D:ABCArduino_LibRemoteXYsrc/classes/RemoteXY_API.h: In member function ‘virtual uint8_t CRemoteXY_API::receiveByte()’:
D:ABCArduino_LibRemoteXYsrc/classes/RemoteXY_API.h:53:35: warning: no return statement in function returning non-void [-Wreturn-type]
virtual uint8_t receiveByte () {};
^
D:ABCArduino_LibRemoteXYsrc/classes/RemoteXY_API.h: In member function ‘virtual uint8_t CRemoteXY_API::availableByte()’:
D:ABCArduino_LibRemoteXYsrc/classes/RemoteXY_API.h:54:37: warning: no return statement in function returning non-void [-Wreturn-type]
virtual uint8_t availableByte () {};
^
D:ABCArduino_LibRemoteXYsrc/classes/RemoteXY_API.h: In member function ‘void CRemoteXY_API::init(const void*, void*,
const char*)’:
D:ABCArduino_LibRemoteXYsrc/classes/RemoteXY_API.h:58:14: warning: unused variable ‘ms’ [-Wunused-variable]
uint32_t ms;
^
D:ABCArduino_LibRemoteXYsrc/classes/RemoteXY_API.h: In member function ‘void CRemoteXY_API::handler()’:
D:ABCArduino_LibRemoteXYsrc/classes/RemoteXY_API.h:127:18: warning: unused variable ‘kp’ [-Wunused-variable]
uint8_t *p, *kp;
^
In file included from D:ABCArduino_LibRemoteXYsrc/RemoteXY.h:170:0,
from srcWiFiPoint_ESP32.cpp:27:
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h: At global scope:
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h:20:3: error: ‘WiFiServer’ does not name a type
WiFiServer *server;
^
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h:21:3: error: ‘WiFiClient’ does not name a type
WiFiClient client;
^
In file included from D:ABCArduino_LibRemoteXYsrc/RemoteXY.h:170:0,
from srcWiFiPoint_ESP32.cpp:27:
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h: In member function ‘virtual uint8_t CRemoteXY::initModule()’:
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h:42:10: error: ‘class WiFiClass’ has no member named ‘softAPdisconnect’
WiFi.softAPdisconnect(true);
^
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h:45:10: error: ‘class WiFiClass’ has no member named ‘mode’
WiFi.mode(WIFI_AP);
^
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h:45:15: error: ‘WIFI_AP’ was not declared in this scope
WiFi.mode(WIFI_AP);
^
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h:46:10: error: ‘class WiFiClass’ has no member named ‘softAP’
WiFi.softAP(wifiSsid, wifiPassword);
^
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h:61:5: error: ‘client’ was not declared in this scope
client.stop();
^
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h:62:5: error: ‘server’ was not declared in this scope
server = new WiFiServer (port);
^
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h:62:18: error: expected type-specifier before ‘WiFiServer’
server = new WiFiServer (port);
^
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h: In member function ‘virtual void CRemoteXY::handlerModule()’:
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h:84:10: error: ‘client’ was not declared in this scope
if (!client) {
^
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h:85:14: error: ‘server’ was not declared in this scope
client=server->available();
^
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h:93:9: error: ‘client’ was not declared in this scope
if (client) {
^
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h: In member function ‘virtual void CRemoteXY::sendByte(uint8_t)’:
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h:118:9: error: ‘client’ was not declared in this scope
if (client) {
^
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h: In member function ‘virtual uint8_t CRemoteXY::receiveByte()’:
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h:138:9: error: ‘client’ was not declared in this scope
if (client) {
^
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h: In member function ‘virtual uint8_t CRemoteXY::availableByte()’:
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h:154:9: error: ‘client’ was not declared in this scope
if (client) {
^
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h: In member function ‘virtual uint8_t CRemoteXY::receiveByte()’:
D:ABCArduino_LibRemoteXYsrc/modules/espcore_wifi.h:148:3: warning: control reaches end of non-void function [-Wreturn-type]
}
^
*** [.piobuildesp32doit-devkit-v1srcWiFiPoint_ESP32.cpp.o] Error 1
============================================== [FAILED] Took 9.83 seconds ==============================================
The terminal process terminated with exit code: 1
Terminal will be reused by tasks, press any key to close it.
4 Reply by Guillaume 2020-02-24 17:51:54
- Guillaume
- Moderator
- Offline
- Registered: 2016-12-23
- Posts: 340
Re: Lib 2.4.3 (14.11.2019) with PlatformIO VS Code
When I compile your example:
Dependency Graph
|-- <RemoteXY> 2.4.3 #b65a904
| |-- <ESP32 BLE Arduino> 1.0.1
|-- <WiFi> 1.0
Yours try to use a third party WiFi library:
Dependency Graph
|-- <RemoteXY> 2.4.3
| |-- <ESP32 BLE Arduino> 1.0.1
|-- <WiFiEspAT> 1.1.1
5 Reply by KissInno 2020-02-24 18:28:23
- KissInno
- Member
- Offline
- Registered: 2019-06-15
- Posts: 23
Re: Lib 2.4.3 (14.11.2019) with PlatformIO VS Code
Guillaume you are genius.
WiFiEspAT uninstalled from PIO Lib Manager, now it compiles without error :-)))
Thanks a lot!
Pages 1
You must login or register to post a reply
-
Взял уже готовый код, но он не хочет работать. Жалуется на строки: DallasTemperature sensors(&oneWire);
Сообщение об ошибке:
Arduino: 1.6.7 (Windows 10), Плата:»Arduino/Genuino Uno»C:UsersUserDocuments1sketchsketch.ino: In function ‘void loop()’:
sketch:74: error: ‘led1’ was not declared in this scope
digitalWrite (led1, HIGH);
^
sketch:78: error: ‘led1’ was not declared in this scope
digitalWrite(led1, LOW);
^
C:UsersUserDocuments1sketchsketch.ino: At global scope:
sketch:88: error: redefinition of ‘OneWire oneWire’
OneWire oneWire(ONE_WIRE_BUS);
^
sketch:7: error: ‘OneWire oneWire’ previously declared here
OneWire oneWire(ONE_WIRE_BUS);
^
sketch:89: error: redefinition of ‘DallasTemperature sensors’
DallasTemperature sensors(&oneWire);
^
sketch:8: error: ‘DallasTemperature sensors’ previously declared here
DallasTemperature sensors(&oneWire);
^
sketch:91: error: redefinition of ‘byte mac []’
byte mac[] = { 0x54, 0x34, 0x41, 0x30, 0x30, 0x31 };
^
sketch:10: error: ‘byte mac [6]’ previously defined here
byte mac[] = { 0x54, 0x34, 0x41, 0x30, 0x30, 0x31 };
^
sketch:93: error: redefinition of ‘EthernetClient client’
EthernetClient client;
^
sketch:12: error: ‘EthernetClient client’ previously declared here
EthernetClient client;
^
sketch:94: error: redefinition of ‘char server []’
char server[] = «*************»; // РёРјСЏ вашего сервера
^
sketch:13: error: ‘char server [14]’ previously defined here
char server[] = «*************»; // РёРјСЏ вашего сервера www.arduino.ru
^
sketch:95: error: redefinition of ‘int buff’
int buff=0;
^
sketch:14: error: ‘int buff’ previously defined here
int buff=0;
^
sketch:96: error: redefinition of ‘const int led’
const int led=5;
^
sketch:15: error: ‘const int led’ previously defined here
const int led=5;
^
C:UsersUserDocuments1sketchsketch.ino: In function ‘void setup()’:
sketch:98: error: redefinition of ‘void setup()’
void setup()
^
sketch:17: error: ‘void setup()’ previously defined here
void setup()
^
C:UsersUserDocuments1sketchsketch.ino: In function ‘void loop()’:
sketch:106: error: redefinition of ‘void loop()’
void loop()
^
sketch:25: error: ‘void loop()’ previously defined here
void loop()
^
sketch:155: error: ‘led1’ was not declared in this scope
digitalWrite (led1, HIGH);
^
sketch:159: error: ‘led1’ was not declared in this scope
digitalWrite(led1, LOW);
^
exit status 1
‘led1’ was not declared in this scopeКод программы:
#include <SPI.h>
#include <Ethernet.h>
#include <OneWire.h>
#include <DallasTemperature.h>#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);byte mac[] = { 0x54, 0x34, 0x41, 0x30, 0x30, 0x31 };
EthernetClient client;
char server[] = «*************»; // имя вашего сервера www.arduino.ru
int buff=0;
const int led=5;void setup()
{
Ethernet.begin(mac);
sensors.begin();
pinMode( led, OUTPUT);
digitalWrite(led, LOW);
}void loop()
{
sensors.requestTemperatures();
if (client.connect(server, 80))
{client.print( «GET /add_data.php?»);
client.print(«temperature=»);
client.print( sensors.getTempCByIndex(0) );
client.print(«&»);
client.print(«&»);
client.print(«temperature1=»);
client.print( sensors.getTempCByIndex(1) );
client.println( » HTTP/1.1″);
client.print( «Host: » );
client.println(server);
client.println( «Connection: close» );
client.println();
client.println();delay(200);
while (client.available())
{
char c = client.read();
if ( c==’1′)
{
buff=1;
}
if ( c==’0′)
{
buff=0;
}
}
client.stop();
client.flush();
delay(100);
}
else
{
client.stop();
delay(1000);
client.connect(server, 80);
}if ( buff==1)
{
digitalWrite (led1, HIGH);
}
else
{
digitalWrite(led1, LOW);
}
delay(500);
}
#include <SPI.h>
#include <Ethernet.h>
#include <OneWire.h>
#include <DallasTemperature.h>#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);byte mac[] = { 0x54, 0x34, 0x41, 0x30, 0x30, 0x31 };
EthernetClient client;
char server[] = «*************»; // имя вашего сервера
int buff=0;
const int led=5;void setup()
{
Ethernet.begin(mac);
sensors.begin();
pinMode( led, OUTPUT);
digitalWrite(led, LOW);
}void loop()
{
sensors.requestTemperatures();
if (client.connect(server, 80))
{client.print( «GET /add_data.php?»);
client.print(«temperature=»);
client.print( sensors.getTempCByIndex(0) );
client.print(«&»);
client.print(«&»);
client.print(«temperature1=»);
client.print( sensors.getTempCByIndex(1) );
client.println( » HTTP/1.1″);
client.print( «Host: » );
client.println(server);
client.println( «Connection: close» );
client.println();
client.println();delay(200);
while (client.available())
{
char c = client.read();
if ( c==’1′)
{
buff=1;
}
if ( c==’0′)
{
buff=0;
}
}
client.stop();
client.flush();
delay(100);
}
else
{
client.stop();
delay(1000);
client.connect(server, 80);
}if ( buff==1)
{
digitalWrite (led1, HIGH);
}
else
{
digitalWrite(led1, LOW);
}
delay(500);
} -
Так приятнее смотреть. Глаза не напрягаются:
#include <SPI.h>
#include <Ethernet.h>
#include <OneWire.h>
#include <DallasTemperature.h>#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);byte mac[] = { 0x54, 0x34, 0x41, 0x30, 0x30, 0x31 };
EthernetClient client;
char server[] = «*************»; // имя вашего сервера www.arduino.ru
int buff=0;
const int led=5;void setup()
{
Ethernet.begin(mac);
sensors.begin();
pinMode( led, OUTPUT);
digitalWrite(led, LOW);
}void loop()
{
sensors.requestTemperatures();
if (client.connect(server, 80))
{client.print( «GET /add_data.php?»);
client.print(«temperature=»);
client.print( sensors.getTempCByIndex(0) );
client.print(«&»);
client.print(«&»);
client.print(«temperature1=»);
client.print( sensors.getTempCByIndex(1) );
client.println( » HTTP/1.1″);
client.print( «Host: « );
client.println(server);
client.println( «Connection: close» );
client.println();
client.println();delay(200);
while (client.available())
{
char c = client.read();
if ( c==‘1’)
{
buff=1;
}
if ( c==‘0’)
{
buff=0;
}
}
client.stop();
client.flush();
delay(100);
}
else
{
client.stop();
delay(1000);
client.connect(server, 80);
}if ( buff==1)
{
digitalWrite (led1, HIGH);
}
else
{
digitalWrite(led1, LOW);
}
delay(500);
}
#include <SPI.h>
#include <Ethernet.h>
#include <OneWire.h>
#include <DallasTemperature.h>#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);byte mac[] = { 0x54, 0x34, 0x41, 0x30, 0x30, 0x31 };
EthernetClient client;
char server[] = «*************»; // имя вашего сервера
int buff=0;
const int led=5;void setup()
{
Ethernet.begin(mac);
sensors.begin();
pinMode( led, OUTPUT);
digitalWrite(led, LOW);
}void loop()
{
sensors.requestTemperatures();
if (client.connect(server, 80))
{client.print( «GET /add_data.php?»);
client.print(«temperature=»);
client.print( sensors.getTempCByIndex(0) );
client.print(«&»);
client.print(«&»);
client.print(«temperature1=»);
client.print( sensors.getTempCByIndex(1) );
client.println( » HTTP/1.1″);
client.print( «Host: « );
client.println(server);
client.println( «Connection: close» );
client.println();
client.println();delay(200);
while (client.available())
{
char c = client.read();
if ( c==‘1’)
{
buff=1;
}
if ( c==‘0’)
{
buff=0;
}
}
client.stop();
client.flush();
delay(100);
}
else
{
client.stop();
delay(1000);
client.connect(server, 80);
}if ( buff==1)
{
digitalWrite (led1, HIGH);
}
else
{
digitalWrite(led1, LOW);
}
delay(500);
} -
Объявите все переменные, которые вы использовали. Пока у меня нет времени… Может кто другой найдется. Вот статья: http://arduino.ru/Tutorial/Variables
-
Первая ошибка 74 строка кода led1 от куда? Было led Копируете текст ошибок и в переводчик более понятно становиться
Arduino programming is an open-source and simple stage that arranges the Arduino board into working with a particular goal in mind. An Arduino code is written in C++ yet with extra capacities and strategies. An Arduino is an equipment and programming stage broadly utilised in hardware.
In this article, we go through three quick fixes for the error ‘was not declared in this scope’.
Also read: How to solve the Tower of Hanoi problem using Python?
What does the error mean?
Every programming language has a concept of Scope. Scope tells us where a specific variable, constant or function is accessible and usable. It refers to the area of code a statement, block, or name. The scope of an entity determines where that entity is usable in other parts of the program. The scope of a block determines where that block can be used in other blocks, and the scope of a name determines where that name can be used in other names.
There are two types of scope in programming languages: local and global. Local scope refers to the identifiers and symbols visible inside a block of code. Global scope, on the other hand, refers to the identifiers and symbols visible outside a block of code.
The error ‘was not declared in this scope’ generally occurs when a variable or function is not accessible to its call. A global variable in Arduino is the variable that is declared outside any function, including the setup() and loop() functions. Any variable declared inside a function or loop has restrictive access and is a local variable.
If any other function calls a local variable, it gives an error. To call any variable or function in any other function, including the setup() and loop() function, it should be declared as a global variable.
Also read: How to stop an Arduino program?
There are the quick fixes for the Arduino error: was not declared in the scope.
Declare the variable
Before assigning a value to the variable, make sure to define it. There are 16 data types commonly used in Arduino coding. Each data type expresses the nature of the value assigned to it. If the data type and value doesn’t match, an error arises. Also, if a variable is assigned any value without its declaration or data type, the error occurs.
Always ensure to declare the variable before the assignment. There are two ways to do this.
There are three variables in the above example – num1, num2 and num3. The variable num1 has been declared separately and assigned to a data type corresponding value in the loop. The variable num2 has been declared and assigned in the same line of code. The variable num3, on the other hand, has directly been assigned a value without its declaration. This causes the error, as shown above.
Other details
There may be errors arising even after proper declaration and assignment of the variable. This may be due to incorrect or absence of the closing brackets, semicolons or improper declaration of functions. Ensure proper use of syntax when defining loops and functions. Every opening in curly brace must be accounted for and closed. Extra closing braces also cause errors. Alongside, semicolons hold their importance. A semicolon missed can cause the entire program to go haywire.
Library folder
Many times, variables call or use functions that require importing a few specific libraries.
In the example above, the variable num calls the square root function – sqrt() from the maths library of Arduino. If we call a function without including its library first, an error occurs. There are multiple inbuilt and standard libraries in Arduino, while a few special libraries must be included separately.
Also read: What is ‘does not name a type’ in Arduino: 2 Fixes.
Dear Sir,
I have copied the Complete_wincock_client_code and Complete_wincock_server_code from https://msdn.microsoft.com/en-us/library/windows/desktop/ms737591(v=vs.85).aspx and https://msdn.microsoft.com/en-us/library/windows/desktop/ms737593(v=vs.85).aspx .
when i am doing compilation, i am getting errors like getaddrinfo() and freeaddrinfo() was not declared in the scope. I am getting for both client and server examples. Please give me a solution to fix this.
//client code
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, «Ws2_32.lib»)
#pragma comment (lib, «Mswsock.lib»)
#pragma comment (lib, «AdvApi32.lib»)
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT «27015»
int __cdecl main(int argc, char **argv)
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
char *sendbuf = «this is a test»;
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
// Validate the parameters
if (argc != 2)
{
printf(«usage: %s server-namen», argv[0]);
return 1;
}
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0)
{
printf(«WSAStartup failed with error: %dn», iResult);
return 1;
}
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
if ( iResult != 0 )
{
printf(«getaddrinfo failed with error: %dn», iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET)
{
printf(«socket failed with error: %ldn», WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR)
{
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET)
{
printf(«Unable to connect to server!n»);
WSACleanup();
return 1;
}
// Send an initial buffer
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR)
{
printf(«send failed with error: %dn», WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf(«Bytes Sent: %ldn», iResult);
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR)
{
printf(«shutdown failed with error: %dn», WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
printf(«Bytes received: %dn», iResult);
else if ( iResult == 0 )
printf(«Connection closedn»);
else
printf(«recv failed with error: %dn», WSAGetLastError());
} while( iResult > 0 );
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
//server_code
#undef UNICODE
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
// Need to link with Ws2_32.lib
#pragma comment (lib, «Ws2_32.lib»)
// #pragma comment (lib, «Mswsock.lib»)
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT «27015»
int __cdecl main(void)
{
WSADATA wsaData;
int iResult;
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET;
struct addrinfo *result = NULL;
struct addrinfo hints;
int iSendResult;
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0)
{
printf(«WSAStartup failed with error: %dn», iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the server address and port
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if ( iResult != 0 )
{
printf(«getaddrinfo failed with error: %dn», iResult);
WSACleanup();
return 1;
}
// Create a SOCKET for connecting to server
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET)
{
printf(«socket failed with error: %ldn», WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}
// Setup the TCP listening socket
iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR)
{
printf(«bind failed with error: %dn», WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
}
freeaddrinfo(result);
iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR)
{
printf(«listen failed with error: %dn», WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
// Accept a client socket
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET)
{
printf(«accept failed with error: %dn», WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
// No longer need server socket
closesocket(ListenSocket);
// Receive until the peer shuts down the connection
do {
iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
if (iResult > 0)
{
printf(«Bytes received: %dn», iResult);
// Echo the buffer back to the sender
iSendResult = send( ClientSocket, recvbuf, iResult, 0 );
if (iSendResult == SOCKET_ERROR)
{
printf(«send failed with error: %dn», WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
printf(«Bytes sent: %dn», iSendResult);
}
else if (iResult == 0)
printf(«Connection closing…n»);
else
{
prWSACleanupintf(«recv failed with error: %dn», WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
}
while (iResult > 0);
// shutdown the connection since we’re done
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR)
{
printf(«shutdown failed with error: %dn», WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
// cleanup
closesocket(ClientSocket);
WSACleanup();
return 0;
}