Mosquitto: Socket error on client <clientname>, disconnecting.

Created on 22 Aug 2017  Â·  24Comments  Â·  Source: eclipse/mosquitto

Hi,

I want to write a MQTT message from an ESP8266/nodeMCU to my raspberry pi which is running Mosquitto broker.

I programmed the ESP board via Arduino IDE, using ESP8266WiFi.h and PubSubClient.h. Mostly copy&paste from the examples.

It connects to the network and then I get the error code from the client.state() function
_-4 : MQTT_CONNECTION_TIMEOUT - the server didn't respond within the keepalive time_
and after wards always
_-2 : MQTT_CONNECT_FAILED - the network connection failed_.

However the connection from the ESP to my Mac which is running also Mosquitto works fine, but I can't explain myself why. I tried allot (e.g. set the ip with the IPAddress type or extended code with WiFi.mode(WIFI_STA);)

I hope you can help me.

ESP CODE:
````

include

include

const char* ssid = "MYSSID";
const char* password = "MYPW";
//const char* mqtt_server = "192.168.178.100";
IPAddress mqtt_server(192, 168, 178, 100);

WiFiClient espClient;
PubSubClient client(espClient);

void setup()
{
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
}

void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
//WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}

Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived
}

void loop()
{
if (client.connect("12rjpwasgdn")) {
client.publish("test","hello world");
client.subscribe("inTopic");
Serial.println("Send: Hello World");
}
else
{
Serial.println("Not Connected");
Serial.println(client.state());
}
delay(1000);
client.loop();
}
````

/etc/mosquitto/conf.d/my.conf:

listener 1883 allow_anonymous true

/var/log/mosquitto/mosquitto.log:
````

...
1503425208: New client connected from xxx.xxx.xxx.x as (c1, k15).
1503425228: Socket error on client , disconnecting.
````

The rest in the Mosquitto folder is default...

Most helpful comment

Well, I just encountered the problem tonight.
And after few hours, I found that I need to connect to mosquitto with different login and password.
Until I do that (no matter that clientId is different) I get the error. I created an other set of login/password for my second device and it works like a charm.

Hope this help for anyone coming here after a google search.

All 24 comments

Why are you trying to connect in every loop?

Philip notifications@github.com wrote:

Hi,

I want to write a MQTT message from an ESP8266/nodeMCU to my
raspberry pi which is running Mosquitto broker.

I programmed the ESP board via Arduino IDE, using ESP8266WiFi.h
and PubSubClient.h. Mostly copy&paste from the examples.

It connects to the network and then I get the error code from
the client.state() function _-4 : MQTT_CONNECTION_TIMEOUT -
the server didn't respond within the keepalive time_ and after
wards always _-2 : MQTT_CONNECT_FAILED - the network connection
failed_.

However the connection from the ESP to my Mac which is running
also Mosquitto works fine, but I can't explain myself why. I
tried allot (e.g. set the ip with the IPAddress type or
extended code with WiFi.mode(WIFI_STA);)

I hope you can help me.

ESP CODE:
````

include

include

const char* ssid = "MYSSID";
const char* password = "MYPW";
//const char* mqtt_server = "192.168.178.100";
IPAddress mqtt_server(192, 168, 178, 100);

WiFiClient espClient;
PubSubClient client(espClient);

void setup()
{
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
}

void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
//WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}

Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length)
{
// handle message arrived
}

void loop()
{
if (client.connect("12rjpwasgdn")) {
client.publish("test","hello world");
client.subscribe("inTopic");
Serial.println("Send: Hello World");
}
else
{
Serial.println("Not Connected");
Serial.println(client.state());
}
delay(1000);
client.loop();
}
````

/etc/mosquitto/conf.d/my.conf:

listener 1883 allow_anonymous true

/var/log/mosquitto/mosquitto.log:
````

...
1503425208: New client connected from xxx.xxx.xxx.x as (c1, k15).
1503425228: Socket error on client , disconnecting.
````

The rest in the Mosquitto folder is default...

Just an example. Could also only doing it in the setup function. But the weird thing is that I get at first the status code -4 and then -2 back in the second repeat...

Is there any solution?

no, it's not "just an example" what you're doing is reconnecting with the same clientid on every loop, which immediately disconnects the existing connection with the same client id, per design. Your current code is along the lines of "it hurts when I do X => stop doing X"

But why is it working on several devices and on several others not?

There's no mention of that in the original report, nor is there enough information to have an opinion on it.

Ok, sorry.
I will start again from the beginning.

I bought 2 identical Sonoff Basic and flashed the lastest Tasmota firmware to it.
Both are booting and connecting to the WIFI, so that I can reach them via their website.

One Sonoff is connecting to my MQTT broker (mosquitto 1.4.10 in RPI3 using Raspbian stretch).
The other one does not connect, The Tasmota console says

00:00:00 Project sonoff_wz Sonoff_wz (Topic sonoff_wz, Fallback sonoff_test1, GroupTopic sonoffs) Version 5.10.0
00:00:00 WIF: Connecting to AP1 WLAN-Access in mode 11N as sonoff_wz-7273...
00:00:07 WIF: Connected
00:00:14 DNS: Initialized
00:00:21 HTP: Web server active on sonoff_wz-7273.local with IP address 192.168.2.127
00:00:29 MQT: Attempting connection...
00:00:43 MQT: Connect failed to 192.168.2.12:1883, rc -2. Retry in 10 sec
00:01:01 MQT: Attempting connection...
00:01:27 MQT: Connect failed to 192.168.2.12:1883, rc -4. Retry in 10 sec
00:01:55 MQT: Attempting connection...
00:02:07 MQT: Connect failed to 192.168.2.12:1883, rc -2. Retry in 10 sec<

The mosquitto log is telling:

1513544715: New connection from 192.168.2.127 on port 1883.
1513544715: New client connected from 192.168.2.127 as sonoff_test1 (c1, k120, u'test').
1513544735: Socket error on client sonoff_test1, disconnecting.
1513544809: New connection from 192.168.2.127 on port 1883.
1513544809: New client connected from 192.168.2.127 as sonoff_test1 (c1, k120, u'test').
1513544829: Socket error on client sonoff_test1, disconnecting.<

So why is one of the both Sonoff working fine and the other one is not connecting?
It get more curios: I started another mqtt broker on my tablet. Here both Sonoffs are connecting.
It seems to be an issue with mosquitto.

What do you mean?

If you have a different issue, please open a separate issue.

Are you shure that this is a different issue?
All the description above fits to my issue.

The other guys may have just one SONOFF with mqtt firmware. So they might not notice, that some work and some don't.

karlp, it's totally ok to say that you don't know how to help further.
sisamiwe, I am having the same issue. The pubsubclient library can connect once, but to me it seems that if I have any other client executing requests on the WiFi then the pubsubclient will lose the connection and not be able to reconnect.

i'm having the same issue

I've been investigating this now for 45 days. After this while I found a few pointers to help towards a solution:
1 - not all esp modules are made equal. Some have better WiFi signal than others
2 - WiFi reception signal affects directly all the software performance. This includes, of course, this error (connect fail)
3 - if you use serial interface to do debugging, it does not matter what levels of reception your ESP sketch reports to you. If you have this problem, please try to establish a direct line of sight from your WiFi router towards your ESP module

Good luck

Well, I just encountered the problem tonight.
And after few hours, I found that I need to connect to mosquitto with different login and password.
Until I do that (no matter that clientId is different) I get the error. I created an other set of login/password for my second device and it works like a charm.

Hope this help for anyone coming here after a google search.

Deamon I did not have authentication enabled in any of my mosquitto services.
After my reply from 8 days ago, I also found that you can setup mosquitto keepalive/timeout parameters in the configuration file /etc/mosquitto/mosquitto.conf and /etc/mosquitto/conf.d/*

This relates to ESP's signal reception and hence general WiFi performance

Hello Im having the same problem I have one sonoff with tasmota working fine but I flashed other esp for another program with mosquitto and one day was working the other gave me the same error, Im using rpi3 with hassio and mosquitto addon installed, any tips on how to solve this? Should I put two passwords and user?

Found out that my router was giving the same ip for two clients, resseted everything set static ip for botg and now its working

I am having same issue RPI3b broker and Openhab is the same host . host is with fix IP.
not sure how to fix it. Guide me to fix it

Just read what everyone said.

On Jun 19, 2018 12:11, sujitrp notifications@github.com wrote:

I am having same issue RPI3b broker and Openhab is the same host . host is with fix IP.
not sure how to fix it. Guide me to fix it

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHubhttps://github.com/eclipse/mosquitto/issues/523#issuecomment-398456459, or mute the threadhttps://github.com/notifications/unsubscribe-auth/ABG7R0YLd5hbOp75MBq3sHLKuQXbQ6g2ks5t-SLBgaJpZM4O_Nap.

I needed to give fix ip for my nodemcu because it was conflicting with other clients on my dhcp list, just entered in my router deleted a couple of clients and gave new ips to each of them now it´s working

Well, I just encountered the problem tonight.
And after few hours, I found that I need to connect to mosquitto with different login and password.
Until I do that (no matter that clientId is different) I get the error. I created an other set of login/password for my second device and it works like a charm.

Hope this help for anyone coming here after a google search.

I have the same issue. Fix IPs and different logins not helps... Please, help me to fix "Socket error on client %name%, disconnecting.". I use Raspbian on RasPi Zero W, home-assistant and mosquitto in docker. Clients are Sonoff relays flashed to Tasmota

I'm using 4 Sonoff Tasmota devices with MQTT authentication enabled and can report the same issue (and verify the workaround provided by @Deamon).

1546101984: New connection from 192.168.0.73 on port 1883.
1546101984: New client connected from 192.168.0.73 as eheim-proxima-250 (c1, k15, u'openhabian').
1546101992: New connection from 192.168.0.157 on port 1883.
1546101992: Socket error on client <unknown>, disconnecting.
1546101992: New connection from 192.168.0.66 on port 1883.
1546101992: Socket error on client <unknown>, disconnecting.
1546101993: New connection from 192.168.0.90 on port 1883.
1546101993: Socket error on client <unknown>, disconnecting.
1546102003: New connection from 192.168.0.157 on port 1883.

I had different client names and the same username / credential as OpenHABian allows to configure just a single credential pair through openhabian-config.

After adding more credentials manually so that each client has its own combination of username and password, it works:

$ mosquitto_passwd -b /etc/mosquitto/passwd user1 secret
$ mosquitto_passwd -b /etc/mosquitto/passwd user2 secret

$ systemctl restart mosquitto.service 
1546102863: mosquitto version 1.4.10 (build date Wed, 17 Oct 2018 19:03:03 +0200) starting
1546102863: Config loaded from /etc/mosquitto/mosquitto.conf.
1546102863: Opening ipv4 listen socket on port 1883.
1546102863: Opening ipv6 listen socket on port 1883.
1546102870: New connection from 192.168.0.73 on port 1883.
1546102870: New client connected from 192.168.0.73 as eheim-proxima-250 (c1, k15, u'eheim-proxima-250').
1546102872: New connection from 192.168.0.90 on port 1883.
1546102872: New client connected from 192.168.0.90 as south-america-64 (c1, k15, u'south-america-64').
1546102873: New connection from 192.168.0.157 on port 1883.
1546102873: New client connected from 192.168.0.157 as dragon-stone-72 (c1, k15, u'dragon-stone-72').
1546102873: New connection from 192.168.0.66 on port 1883.
1546102873: New client connected from 192.168.0.66 as samurai-stone-64 (c1, k15, u'samurai-stone-64').

I'm going to close this issue, it has become a bit of a mix of different people with different issues and not enough detail to sort anything out. If you still have a problem, please open a new issue and provide the details there.

@jay-pee I notice you're sending a message every loop, followed by delay(1000); client.loop();. You're also attempting to connect every loop. A better approach may be:

void loop() {
  // connect to mqtt if not already connected
  if (!client.connected()) {
    client.connect(...);
    client.subscribe(...);
  }
  // if we're connected, then publish our message
  if (client.connected()) {
    client.publish(...);
  }
  // and now wait for 1s, regularly calling the mqtt loop function
  for (int i=0; i<1000; i++) {
    client.loop();
    delay(1);
  }
}

The PubSubClient documentation notes:

loop(): This should be called regularly to allow the client to process incoming messages and maintain its connection to the server.

I stopped this project but know consider working on it again because some good ideas where mentioned. Thank you for your help.

Was this page helpful?
0 / 5 - 0 ratings