Sergey Ivanov
Sergey Ivanov

Reputation: 3929

Socket connection refused after first message

I communicate Python with Matlab via sockets. However, even before going there, I want to test sockets with netcat. So I establish server using nc -lkp 25771, and make Python client to send a message to this server:

import socket
host = 'localhost'
port = 25771
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
s.send('Hello there')
s.close()

After running python client.py server prints out 'Hello there'; however, after I try to run client script one more time it raises exception.

Traceback (most recent call last): File "client.py", line 13, in s.connect((host,port)) File "/usr/lib/python2.7/socket.py", line 224, in meth return getattr(self._sock,name)(*args) socket.error: [Errno 111] Connection refused

Why the same command raises the error second time? What changes after my first command?

Upvotes: 3

Views: 1813

Answers (1)

Praveen
Praveen

Reputation: 406

You are using traditional version of netcat (netcat-traditional) which doesn't support -k option. you can confirm checking the man page of your netcat by typing man nc in your terminal .

Install the netcat-openbsd version using the command sudo apt-get install netcat-openbsd

now switch to netcat-openbsd version using the command

sudo update-alternatives --config nc and choose the netcat-openbsd .

now you can use nc -lk 25771 . this listens on port 25771 for multiple connections .

you can also use the commands discussed here Netcat: using nc -l port_number instead of nc -l -p port_number

Upvotes: 0

Related Questions