Socket error 111 connection refused

Добрый день. Возникла проблема при проверке сайта. Работа с сокетами - Socket error [111]: Connection refused. Из-за этого не работает нормально аналитика. В чем может быть проблема?используем 1C-Bitrix: VM 3.1CentOS 6.0 (32-bit)Может кто знает в чем может быть проблема? Или кто сталкивался с такой:?Спасибо![FILE ID=603083]

как я решал эту проблему

тоже напоролся дважды  при переводе сайта из1251 на ю-8 и уходе из облака в коробку на Б-24

ошибка пакостная действительно, на нее завязано много полезных функций, которые попросту не станут работать

начинаем сначала

комбинация такая Linux CentOS 7.4 + nginx 1.12.2 + тело

1. раздобыть сертификат SSL
у нас изначально стоял КОМОД и по принципу «от добра добра не ищут» поперся обратно к ним же, т.к. дают на 3 месяца бесплатный с возможностью продления
самоподписанты — дело хорошее, но до поры — до времени и не для публичного сайта

для знакомых с английским языком не по наслышке — можно напрямую написать через сайт КОМОДа, для нуждающихся в шефской помощи — мне лично понравился сервис и отношение к клиентам на FirstSSL
у КОМОДа примерно час, у этих минут 30 заняло

беда!:  КОМОД пришлет 4 файла, из которых 1 — это сам сертфикат, а три других надо саморучно подвергнуть конкатенации, дабы слепить из них *.ca-bundle файл
одна ошибка в последовательности и сертификат уже не пройдет проверку на ssllabs  и прочих подобных ресурсах, будет или некорректно построеная цепочка, или отсутствие цепочки или еще чего не так, и снова — все на «НЕРУССКОМ ЯЗЫКЕ»:

  • Root      CA Certificate — AddTrustExternalCARoot.crt
  • Intermediate      CA Certificate — COMODORSAAddTrustCA.crt
  • Intermediate      CA Certificate — COMODORSADomainValidationSecureServerCA.crt
  • Your      Free SSL Certificate — your_domain_ru.crt

вот тут как раз и зарыта большая собака, т.к. корневой сертификат надо класть в конец файла а оба иммедиата в начало но в строго определенном порядке №1-№2_корень

если тип сертификата предполагает не 1 и не 2 промежуточных — то заплутать очень даже большая вероятность!

от FirstSSL же пришло все готовенькое, оставалось только засунуть в нужное место, т.е. сам сертификат и собраный *.ca-bundle

2. теперь пытаемся пробраться в каталог /etc/nginx/ssl/ и засунуть туда оба эти произведения ИТ-исскуства, предварительно хорошенько запомнив их названия! для этой цели я использовал классический прием по типу Мойдомен_ру.*
после того, как они уже там — поиграться с правами на доступ

3. теперь надо зайти в каталог /etc/nginx/bx/conf/ и отредактировать файл ssl.conf

там уже будут три строчки:

SSL_certificete_file
SSL_certificste_key_file
dhparam_file

которые относятся ко встроенному сертификату Битрик Вэбокружение, которому никто не доверяет все равно
приводим их к такому виду :

#SSL_certificete_file
#SSL_certificste_key_file
dhparam_file

и выше пишем все с точностью, меняя только название и расширение для своих сертификатов (по умолчанию там будет *.pem, и придется заменить на *.crt & *.key)

не забываем перезапустить сам nginx после всех этих манипуляций


если же у вас просто апач, то принцип то действий похожий, вот только каталог будет /etc/pki/tls// и в нем две папочки
— cert  для сертификатов
-private для ключей

также рекомендуется перезапустить апач

радости не было конца, думал, что все уже решил, однако не тут то было! часть ошибок с сокетами ушла, которая ниже этажом, а сама строка Работа с сокетами = по прежнему fail…..

бежим в файл /etc/hosts и видим такую печальную картину

127.0.0.1     local  local.localdomain
::1               local  local.domain  local6 local.localdomain6

пустое место

#ANSIBLE MANAGED…… НЕ  совать ничего после этой строчки
ваш_внутренний адрес_сервера    имя сервера  имя_сервера.домен

если все работает только внутри сети = это еще куда ни шло, но когда выпустили джинна наружу, то вместо пустоты выше последних строк
пишем

ваш_внутренний адрес_сервера      DNS_адрес_узла
(192.168.1.23              my_domain.*)
причем записать надо разом оба варианта с www и без
можно даже употребить формочку

#bx-host
(192.168.1.23              my_domain.*)
если у вас на сервре будет крутиться несколько сайтов
и для некоторых сетей может потребоваться добавление и внешнего IP тоже, хотя не всегда

только после ВСЕХ этих манипуляций все прекрасно завелось и поехало, замок позеленел с досады, что больше не к чему придраться и  придется открывать страницу

и только после того как — удалось поднять Push, ибо он тоже на это завязан

— На основе оценок
2

человек

При прохождении теста настроек Битрикса часто вылазит ошибка Socket error [111]: Connection refused, причин может быть несколько. Чтобы понять в чем именно причина, можно посмотреть логи проверки, но лучше в командной строке ввести аналогичную команду (по сути, битрикс ее выполняет).


  	curl https://ваш_сайт
	#Если сайт через SSL работает
  	curl https://ваш_сайт:443

Битрикс не видит своего домена по URL

Если наблюдается такая ошибка (ее можно посмотреть в логах проверки битрикса), то необходимо в /etc/hosts прописать 127.0.0.1 ваш_сайт и ваш.IP ваш_сайт (все с новой строчки).

Ошибка с SSL.
curl: (60) server certificate verification failed.

Еще один распространенный вариант — неправильная установка SSL сертификата. Даже если у вас сайт открывается с зеленой полоской, нужно проверить еще раз тут — https://www.sslshopper.com/ssl-checker.html или в командной строке ввести запрос на сайт через curl.

Лечить данную проблему нужно правильной установкой SSL (логично). Проблему помогает решить внесение ca-bundle к crt сертификату. Чтобы не генерировать ca-bundle, просто возьмите себе тут — https://www.namecheap.com/support/knowledgebase/article.aspx/9393/69/where-do-i-find-ssl-ca-bundle (искать по названию).

curl: (7) Failed connect to crm.domain.ru:443;
Connection refused

Это значит, что исходящее обращение блокируется. Скорее всего, порты для вашего домена закрыты. Чтоыб проверить, нужно ввести команду


  nmap -p80,443 crm.domain.ru

#если выдаст такое, значит порты закрыты
Starting Nmap 6.40 ( http://nmap.org ) at 2017-08-29 18:07 MSK
Nmap scan report for crm.capitalest.ru (192.2.2.2)
Host is up (0.00043s latency).
PORT    STATE  SERVICE
80/tcp  closed http
443/tcp closed https

Данная проблема лечится, как и писал выше, добавлением в /etc/hosts строчки 127.0.0.1 ваш_сайт и ваш.IP ваш_сайт (все с новой строчки).


Вас могут заинтересовать следующие услуги

Содержание

  1. ConnectionRefusedError: [Errno 111] Connection Refused
  2. Why the ConnectionRefusedError: [Errno 111] Connection refused Occurs in Python
  3. How to Solve the ConnectionRefusedError: [Errno 111] Connection refused in Python
  4. Use gethostbyname
  5. Conclusion
  6. «socket.error: [Errno 111] Connection refused» while training on ADE20K #215
  7. Comments
  8. ConnectionRefusedError: [Errno 111] Connection refused
  9. ss -lt
  10. ss -lt
  11. 1 Answer 1
  12. socket.error: [Errno 111] Connection refused [JIRA: CLIENTS-41] #375
  13. Comments
  14. connect() failed (111: Connection refused) while connecting to upstream
  15. 8 Answers 8
  16. Summary:

ConnectionRefusedError: [Errno 111] Connection Refused

This error indicates that the client cannot connect to the port on the server script’s system. Since you can ping the server, it should not be the case.

This might be caused by many reasons, such as improper routing to the destination. The second possibility is that you have a firewall between your client and server, which may be either on the server or the client.

There shouldn’t be any routers or firewalls that may stop the communication since, based on your network addresses, both the server and the client should be on the same Local Area Network.

Why the ConnectionRefusedError: [Errno 111] Connection refused Occurs in Python

This error arises when the client cannot access the server because of an invalid IP or port or if the address is not unique and used by another server.

The connection refused error also arises when the server is not running, so the client cannot access the server as the server should accept the connection first.

How to Solve the ConnectionRefusedError: [Errno 111] Connection refused in Python

Try to keep the receiving socket as accessible as possible. Perhaps accessibility would only take place on one interface, which would not impact the Local Area Network.

On the other hand, one case can be that it exclusively listens to the address 127.0.0.1 , making connections from other hosts impossible.

When you run the command python server.py , you will receive the message Got connection . At the same time when you run the command python client.py , you will receive a message from the server.

The DNS resolution can be the other reason behind this problem. Since the socket.gethostname() returns the hostname, an error will be returned if the operating system cannot translate it to a local address.

The Linux operating system can edit the host file by adding one line.

Use gethostbyname

Thus, you must use the identical technique on the client and server sides to access the host. For instance, you would apply the procedure described above in a client’s case.

You can also access through local hostname hostnamehost = socket.gethostname() or specific name for local host host = socket.gethostbyname(«localhost») .

Conclusion

ConnectionRefusedError in Python arises when the client cannot connect to the server. Several reasons include the client not knowing the IP or port address and the server not running when the client wants to connect.

There are several methods mentioned above to resolve this connection issue.

Zeeshan is a detail oriented software engineer that helps companies and individuals make their lives and easier with software solutions.

Источник

«socket.error: [Errno 111] Connection refused» while training on ADE20K #215

I am getting following error after few data iteration @ 551/22210:

File «train.py», line 201, in
trainer.training(epoch)
File «train.py», line 142, in training
for i, (data, target) in enumerate(tbar):
File «/usr/local/lib/python2.7/dist-packages/tqdm/_tqdm.py», line 930, in iter
for obj in iterable:
File «/usr/local/lib/python2.7/dist-packages/mxnet/gluon/data/dataloader.py», line 222, in next
return self.next()
File «/usr/local/lib/python2.7/dist-packages/mxnet/gluon/data/dataloader.py», line 218, in next
idx, batch = self._data_queue.get()
File «/usr/lib/python2.7/multiprocessing/queues.py», line 117, in get
res = self._recv()
File «/usr/local/lib/python2.7/dist-packages/mxnet/gluon/data/dataloader.py», line 88, in recv
return pickle.loads(buf)
File «/usr/lib/python2.7/pickle.py», line 1388, in loads
return Unpickler(file).load()
File «/usr/lib/python2.7/pickle.py», line 864, in load
dispatchkey
File «/usr/lib/python2.7/pickle.py», line 1139, in load_reduce
value = func(*args)
File «/usr/local/lib/python2.7/dist-packages/mxnet/gluon/data/dataloader.py», line 53, in rebuild_ndarray
fd = multiprocessing.reduction.rebuild_handle(fd)
File «/usr/lib/python2.7/multiprocessing/reduction.py», line 156, in rebuild_handle
conn = Client(address, authkey=current_process().authkey)
File «/usr/lib/python2.7/multiprocessing/connection.py», line 169, in Client
c = SocketClient(address)
File «/usr/lib/python2.7/multiprocessing/connection.py», line 308, in SocketClient
s.connect(address)
File «/usr/lib/python2.7/socket.py», line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused

I am using latest nightly of MXNET along with Sync BatchNorm, This error comes with and without SyncBatchNorm layer.

I am using MXNET docker

Any help is much appreciated.

The text was updated successfully, but these errors were encountered:

Источник

ConnectionRefusedError: [Errno 111] Connection refused

I get «connection refused 111» when trying to communicate over sockets in Python. When the connection is refused, THE LISTENER STOPS LISTENING. Same problem occurs using import of multiprocessing.connection, socket, zeromq.

My feeling is that the link between Python and the OS/network doesn’t work. However the NC and socket commands issued in a ubuntu terminal can communicate over the same port.

Notwithstanding the inconvenience it’s causing me, there is obviously a severe security risk if an invalid connection request causes a socket to stop listening. Ideal for denial of service attacks.

I have two programs:

When I start the listener (f5 in IDLE), it seems to start ok.

and the socket starts listening:

ss -lt

State Recv-Q Send-Q Local Address:Port Peer Address:Port Process

LISTEN 0 1 192.168.1.100:16001 0.0.0.0:*

However, when I start the client (f5 in IDLE) I get this:

and the listening socket disappears.

ss -lt

State Recv-Q Send-Q Local Address:Port Peer Address:Port Process

LISTEN 0 5 127.0.0.1:ipp 0.0.0.0:* LISTEN 0 1 127.0.0.1:36093
0.0.0.0:*
LISTEN 0 5 [::1]:ipp [::]:*

Ive tried changing port numbers, setting FW rules, IP addresses from hard-coded to «localhost», . remote client (on Windows) etc etc. Nothing works although symptoms vary.

Ive tried programming the connection using the «socket import» and have exactly the same results. zeromq doesn’t work either.

However the NC and socket commands issued in a terminal can communicate over the same port.

fwiw Im running Ubuntu 20.04.2 LTS. Apart from the one client I tried on windows, all testing is done on a single ubuntu system. Its a fairly new install, so its unlikely I’ve broken something.

Please can someone tell me what I’m doing wrong?

My feeling is that the link between Python and the OS/network doesn’t work.

Notwithstanding the inconvenience it’s causing me, there is obviously a severe security risk if an invalid connection request causes a socket to stop listening. Ideal for denial of service attacks.

1 Answer 1

I couldn’t reproduce your issue, thus not sure what’s the problem. But, some remarks.

I added a simple ping-pong exchange to your code:

and also changed the listening address to one from the link-local subnet 127.0.0.0/8 .

Then simply using 2 terminal tabs/windows, run t2.py then t1.py 3 times:

The server process continues to run, as expected. The client tab:

Please pay attention. You may think these things you named are the same — but they are significantly different:

multiprocessing.connection, socket, zeromq.

The python-builtin import socket module is direct translation of the classic BSD sockets API. The «sockets API» is what defines such things as: port, listening on a port, connecting to a port, accepting a connection, send , recv , close and a few more functions. A book on network programming may help (e.g. this one as a random example — I don’t endorse it). The sockets API is almost 40 years old, so you’ll also easily find free learning materials online.

Next, import multiprocessing module. It’s a completely different story. It provides helpers for multi-process Python programs. Those create multiple PIDs and can run on multiple processor cores. Almost certainly you’ll want these processes to talk to each other to do useful work. This is where sockets come handy: since processes are isolated by OS from each other, network provides a way to build that communication (even if it’s localhost-only). The sub-module multiprocessing.connection provides ergonomic helpers exactly for that.

Next, ØMQ is altogether a separate project (it’s not python-builtin; neither it’s python-specific). It does something interesting; it redefines another «socket API». ØMQ socket ≠ BSD socket. Zeromq sockets can do things which BSD sockets can’t (pub/sub, fanout, app-level routing). Zeromq sockets are built «on top of» BSD sockets; if you have troubles with the lower-level API, I would recommend to approach ZMQ only after you get comfortable with bare basic sockets.

Nothing works although symptoms vary.

Again, you should get comfortable with interpreting network failure modes. The raised error codes have precisely defined meanings. For example, the classic Connection refused errno 111 means that the initial SYN packet to the host you connect() to was responded with an RST packet instead of the normal SYN+ACK — which usually happens when there’s no program listening to the given port on the remote computer you connect() to.

One more remark with regards to your security concerns. You should always assume that the network is adversarial (hostile), regardless if it’s indeed true at that point in space & time — even the localhost network. This is why the higher-level multiprocessing API has the authkey parameter; it’s practically always needed. The password bytestring is one of the worst values for authkey imaginable, try something better. An active network adversary could, theoretically, explain your issue; there’s something called «RST injection attack». You might’ve simply exhausted the listen backlog/SOMAXCONN, too.

Источник

socket.error: [Errno 111] Connection refused [JIRA: CLIENTS-41] #375

I am using RIAK Python client for my project and RIAK amazon instance.I got this error while running my project and its related to RIAK instance.My error log is :-
Traceback (most recent call last):
File «ironjob/ai/index.py», line 36, in application
returnval = mManager.process(api)
File «ironjob/ai/ironMainManager.py», line 94, in process
return self.mUserManager.process(listitem)
File «ironjob/ai/ironUserManager.py», line 27, in process
return self.userVerification(listitem)
File «ironjob/ai/ironUserManager.py», line 62, in userVerification
self.mCacheManager.addData(BUCKET_AI, datadict[KEY_SESSID], sessionData, cacheStart=1, cacheEnd=3, timeout=60)
File «ironjob/ai/ironCacheManager.py», line 55, in addData
self.mRiakClient.addData(bucket, key, dataVals, nestedKey=innerKey, timeout=timeout)
File «ironjob/ai/ironRiakClient.py», line 53, in addData
currentData = <> if bucket.get(key).get_data() == None else bucket.get(key).get_data()
File «build/bdist.linux-x86_64/egg/riak/bucket.py», line 326, in get
File «build/bdist.linux-x86_64/egg/riak/riak_object.py», line 459, in reload
File «build/bdist.linux-x86_64/egg/riak/transports/pbc.py», line 251, in get
File «build/bdist.linux-x86_64/egg/riak/transports/feature_detect.py», line 76, in quorum_controls
File «build/bdist.linux-x86_64/egg/riak/util.py», line 61, in get
File «build/bdist.linux-x86_64/egg/riak/transports/feature_detect.py», line 95, in server_version
File «build/bdist.linux-x86_64/egg/riak/transports/pbc.py», line 178, in _server_version
File «build/bdist.linux-x86_64/egg/riak/transports/pbc.py», line 206, in get_server_info
File «build/bdist.linux-x86_64/egg/riak/transports/pbc.py», line 528, in send_msg_code
File «build/bdist.linux-x86_64/egg/riak/transports/pbc.py», line 559, in send_pkt
File «build/bdist.linux-x86_64/egg/riak/transports/pbc.py», line 113, in maybe_connect
File «build/bdist.linux-x86_64/egg/riak/transports/connection.py», line 166, in maybe_connect

File «», line 1, in connect
socket.error: [Errno 111] Connection refused

Please help me out.Thanks in advance.

The text was updated successfully, but these errors were encountered:

Connection refused means exactly what it says. Whatever port you tried to connect to, the Riak server is not listening on or is otherwise inaccessible. Possible causes/solutions:

Источник

connect() failed (111: Connection refused) while connecting to upstream

I’m experiencing 502 Gateway errors when accessing a PHP file in a directory ( http://example.com/dev/index.php ). The logs simply says this:

I’ve never experienced this before. What is the solution for this type of 502 Gateway error?

This is the nginx.conf :

8 Answers 8

It sounds like you haven’t started and configured the backend for Nginx. Start php-fpm and add the following to nginx.conf , in the http context:

This answer is only for those who get an error like this:

connect() failed (111: Connection refused) while connecting to upstream, client . fastcgi://[::1]:9000

Rewrite your nginx config to use ip, not dns. For instance, 127.0.0.1 instead of localhost , or remove the ipv6 alias from /etc/hosts.

Got errors like this too. Problem was my abstract backend referencing two servers. php-fpm was only listing to socket.

Had the same problem with proxied requests to a Node server listening on port 5000. Requests would result with 200 OK but sometime 502 Bad Gateway randomly. NGINX showed the error:

  1. Set node HTTP server to listen strictly for ipv4 by including localhost as host: server.listen(5000, ‘localhost’);
  2. Removed any ipv6 listen directives ( listen [::]:80; or listen [::]:443 ssl default_server; ).
  3. Changed location block proxy_pass to use IPs: proxy_pass http://127.0.0.1:5000 (not proxy_pass http://localhost:5000 ).

Hope this helps someone.

In my case the error was a bad location for the error_log file for php5.6-fpm service and thus the php-fpm service was failing to start and nginx was not able to connect to it. You can find it in /etc/php/5.6/fpm/php.ini (you can replace 5.6 with the version you are running).

Same problem has occured for me and finally I found firewalld was blocking required ports after installation and I was missing to open ports in firewall (port 9000 in your logs).

Just in case somebody is deperately trying to fix their problem just to realize there is nothing wrong with their reverse proxy setup:

In my case, the error persisted even after I’ve removed all location directives but a single one that only provides static content.

The error message was caused because Nginx wasn’t able to log it’s log to the syslog server:

Summary:

If you are using a syslog log server, make sure it is available. To test whether the error originates from the logging setup, comment out all logging configs so that Nginx falls back to the native logging scheme.

I hope this saves some people time debugging a fully valid reverse proxy config, just to fid the error somewhere else 😀

Источник

  1. Why the ConnectionRefusedError: [Errno 111] Connection refused Occurs in Python
  2. How to Solve the ConnectionRefusedError: [Errno 111] Connection refused in Python
  3. Conclusion

ConnectionRefusedError: [Errno 111] Connection Refused

This error indicates that the client cannot connect to the port on the server script’s system. Since you can ping the server, it should not be the case.

This might be caused by many reasons, such as improper routing to the destination. The second possibility is that you have a firewall between your client and server, which may be either on the server or the client.

There shouldn’t be any routers or firewalls that may stop the communication since, based on your network addresses, both the server and the client should be on the same Local Area Network.

Why the ConnectionRefusedError: [Errno 111] Connection refused Occurs in Python

This error arises when the client cannot access the server because of an invalid IP or port or if the address is not unique and used by another server.

The connection refused error also arises when the server is not running, so the client cannot access the server as the server should accept the connection first.

Code example:

# server code
import socket

s = socket.socket()
host = socket.gethostname()
port = 1717
s.bind((host, port))

s.listen(5)
while True:
    c,addr = s.accept()
    print("Got connection ", addr)
    c.send("Meeting is at 10am")
    c.close()
# client code
import socket

s = socket.socket()
host = '192.168.1.2'
port = 1717

s.connect((host,port))
print(s.recv(1024))
s.close

Output:

socket.error: [Errno 111] Connection refused

How to Solve the ConnectionRefusedError: [Errno 111] Connection refused in Python

Try to keep the receiving socket as accessible as possible. Perhaps accessibility would only take place on one interface, which would not impact the Local Area Network.

On the other hand, one case can be that it exclusively listens to the address 127.0.0.1, making connections from other hosts impossible.

Code example:

import socket

s = socket.socket()
host = socket.gethostname()
port = 1717
s.bind(('', port))

s.listen(5)
while True:
    c,addr = s.accept()
    print("Got connection ", addr)
    c.send("The Meeting is at 10 am")
    c.close()
import socket

s = socket.socket()
host = socket.gethostname()
port = 1717
s.bind(('', port))

s.connect((host, port))
print(s.recv(1024))
s.close()

Output:

Got connection('192.168.1.2')
The meeting is at 10 am

When you run the command python server.py, you will receive the message Got connection. At the same time when you run the command python client.py, you will receive a message from the server.

The DNS resolution can be the other reason behind this problem. Since the socket.gethostname() returns the hostname, an error will be returned if the operating system cannot translate it to a local address.

The Linux operating system can edit the host file by adding one line.

host = socket.gethostname()
port = 1717
s.bind((host,port))

Use gethostbyname

host = socket.gethostbyname("192.168.1.2")
s.bind((host, port))

Thus, you must use the identical technique on the client and server sides to access the host. For instance, you would apply the procedure described above in a client’s case.

You can also access through local hostname hostnamehost = socket.gethostname() or specific name for local host host = socket.gethostbyname("localhost").

host = socket.gethostname()
s.connect((host, port))
host = socket.gethostbyname("localhost")
s.connect((host, port))

Conclusion

ConnectionRefusedError in Python arises when the client cannot connect to the server. Several reasons include the client not knowing the IP or port address and the server not running when the client wants to connect.

There are several methods mentioned above to resolve this connection issue.

I’ve bought my first Raspberry Pi 3B+ last week and started working on my project but I seem to be stuck at this point. I’ve looked through a hundred different posts but none of the solutions seem to work for me.

Brief info on what I’m trying to accomplish:
A python script the listens for button presses needs to be started at boot (regardless of if I’m booting in headless mode or full desktop) and needs to be able to control MPD playback (python-mpd2)

I’ve tried:
— adding ‘python /home/pi/Documents/Jukebox/Listener.py’ to /etc/rc.local while enabling rc.local and making it executable
— creating a service ‘listener.service’ in the /etc/systemd/system/ folder with the following code:

[Unit]
Description=start listening to button presses
Wants=network-online.target
After=network-online.target

[Service]
Type=simple
User=pi
WorkingDirectory=/home/pi
ExecStart=/home/pi/Documents/Jukebox/Listener.py

[Install]
WantedBy=multi-user.target

My python script is very basic and just assign the GPIO inputs, listens to changes and executes a MPD command:

#!/usr/bin/python
import RPi.GPIO as GPIO
import mpd
import time
from toggleplayback import toggleplaypauze 
GPIO.setmode(GPIO.BCM)
GPIO.setup(17,GPIO.IN,pull_up_down = GPIO.PUD_DOWN)
GPIO.add_event_detect(17, GPIO.RISING, bouncetime = 200)
GPIO.setup(18,GPIO.IN,pull_up_down = GPIO.PUD_DOWN)
GPIO.add_event_detect(18, GPIO.RISING, bouncetime = 200)
GPIO.setup(20,GPIO.IN,pull_up_down = GPIO.PUD_DOWN)
GPIO.add_event_detect(20, GPIO.RISING, bouncetime = 200)
client = mpd.MPDClient()
client.connect("localhost",6600)

def toggleplayback(self):
    status=client.status()
    print(status['state'])
    if (status['state'] == "pause"):
        client.pause(0)
    elif (status['state'] == "stop"):
        client.play(1)
    else :
        client.pause(1)

def nextsong(self):
    client.next()

def previoussong(self):
    client.previous()


GPIO.add_event_callback(17,toggleplayback)
GPIO.add_event_callback(18,nextsong)
GPIO.add_event_callback(20,previoussong)

while True:
    time.sleep(0.01)

When I test the service by enabling it and starting it, it works perfectly. However, when I restart the service is not started by default and if I check the status of the service I get the following error:

pi@raspberrypi:~ $ systemctl status listener.service    
listener.service - start listening to button presses
       Loaded: loaded (/etc/systemd/system/listener.service; enabled; vendor preset: enabled)
       Active: failed (Result: exit-code) since Sun 2019-01-13 16:04:44 CET; 42s ago
      Process: 398 ExecStart=/home/pi/Documents/Jukebox/Listener.py (code=exited, status=1/FAILURE)
     Main PID: 398 (code=exited, status=1/FAILURE)

    jan 13 16:04:44 raspberrypi Listener.py[398]:   File "/home/pi/Documents/Jukebox/Listener.py", line 14, in <module>
    jan 13 16:04:44 raspberrypi Listener.py[398]:     client.connect("localhost",6600)
    jan 13 16:04:44 raspberrypi Listener.py[398]:   File "/home/pi/.local/lib/python2.7/site-packages/mpd/base.py", line 641, in connect
    jan 13 16:04:44 raspberrypi Listener.py[398]:     self._sock = self._connect_tcp(host, port)
    jan 13 16:04:44 raspberrypi Listener.py[398]:   File "/home/pi/.local/lib/python2.7/site-packages/mpd/base.py", line 604, in _connect_tcp
    jan 13 16:04:44 raspberrypi Listener.py[398]:     raise err
    jan 13 16:04:44 raspberrypi Listener.py[398]: socket.error: [Errno 111] Connection refused
    jan 13 16:04:44 raspberrypi systemd[1]: listener.service: Main process exited, code=exited, status=1/FAILURE
    jan 13 16:04:44 raspberrypi systemd[1]: listener.service: Unit entered failed state.
    jan 13 16:04:44 raspberrypi systemd[1]: listener.service: Failed with result 'exit-code'.

I’m now officially out of ideas on what to do. If anyone can give me a new idea or an explanation about why what I’m trying to do is wrong and how I should be doing this, please advise!

Thanks

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Soapui mock dispatch error missing response
  • Socket error 11003
  • Soapui error loading wsdl
  • Soapui error getting response javax net ssl
  • Socket error 11001host not found

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии