Socket connection won't close? - python

I'm trying to write a simple server program that prints the data sent to it, or quits if the data is "quit", "exit", or "stop":
HOST = ""
PORT = 37720
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(1)
while(1):
conn, addr = server.accept()
data = conn.recv(1024)
if not data: break
inData, inUrl = json.loads(data)
if inData == "quit" or inData == "exit" or inData == "stop":
print("Quitting")
conn.close()
break
else:
conn.send("Received")
print(inData)
It does what I expect, except that when I try to run the server again once it's quit, I get:
Traceback (most recent call last):
File "./s", line 14, in <module>
server.bind((HOST, PORT))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
I assume this means the connection wasn't closed. How can I close it to prevent this? I tried the conn.close(), but it didn't fix anything.

You need to set SO_REUSEADDR flag.
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

Related

Unix socket [Errno 95] in Python

I am trying to bind unix socket.
import socket
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
s.bind("chatsock")
s.listen(1)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
However I got this Error:
File "test.py", line 4, in <module>
s.bind("chatsock")
OSError: [Errno 95] Operation not supported
Do you have some idea why? Thank you for reply.

OSError: [WinError 10022] An invalid argument was supplied in socket.listen(2)

I am running this server code on Visual Studio Code for a server project:
import socket
from _thread import *
import sys
server = "192.168.0.4"
port = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((server, port))
except socket.error as e:
str(e)
s.listen(2)
print("Waiting for connections...")
print("Server Started!")
def threaded_client(conn):
conn.send(str.encode("Connected"))
reply = ""
while True:
try:
data = conn.recv(2048)
reply = data.decode("utf-8")
if not data:
print("Disconnected!")
break
else:
print("Received: ", reply)
print("Sending: ", reply)
conn.sendall(str.encode(reply))
except:
break
print("Lost Connection!")
conn.close()
while True:
conn, addr = s.accept()
print("Connected to: ", addr)
start_new_thread(threaded_client, (conn,))
And for some reason I am getting an error like this:
Traceback (most recent call last):
File "c:/Users/sande/Desktop/Vihaan/ThirdPartySoftware/Python/VisualStudiosCode/RPSOnline/server.py", line 16, in <module>
s.listen(2)
OSError: [WinError 10022] An invalid argument was supplied
Pls help me in why this is happening. I tried re - writing the code, but it didn't work.

Python Socket getattr requires integer

I'm trying to use the socket object in one of my python codes and it fails at this line:
#!/usr/bin/python
import subprocess,socket
HOST = '127.0.0.1'
PORT = '443'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Yo')
while 1:
data = s.recv(1024)
if data == "quit": break
proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdoutput1 = proc.stdout.read() + proc.stderr.read()
s.send(stdoutput)
s.send('Bye')
s.close()
It fails at: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
File "C:\Python27\lib\socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
TypeError: an integer is required
It's telling me an integer is required in the parameters when I can't see why it would be. It calls this method from socket.py:
def meth(name,self,*args):
return getattr(self._sock,name)(*args)
You have misunderstood the error message, and are looking at the wrong line. It is the s.connect() call that fails:
>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.connect(('127.0.0.1', '443'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
TypeError: an integer is required
Note that it is not the socket.socket() call that failed here, it is the s.connect() call instead, because '443' is not a valid port number.
Port numbers must be integers, not strings; correct your PORT variable:
PORT = 443 # make this an integer
With that change connecting works (provided the port is connectable):
>>> s.connect(('127.0.0.1', 443))

Python client server to send a file Beginner Error

I am trying to do simple code to send file from the client to the server after saving in t some data.
I am a beginner so I can't figure where the problem is or what is the missing function or line in my code
The Server :
import socket
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8000))
server_socket.listen(0)
BUFFER_SIZE = 1024
conn, addr = server_socket.accept()
print ('Got connection from', addr)
while 1:
data = conn.recv(BUFFER_SIZE)
if not data:
break
fileREC=open (data , 'rb')
The Client
import socket
client_socket = socket.socket()
client_socket.connect(("192.168.1.4", 8000))
BUFFER_SIZE = 1024
TextFile= open ("TextFile","w")
TextFile.write("Here is the file")
TextFile.write("Writing data")
TextFile.close()
f=open (TextFile , 'wb')
print ("Writing the file to binart ")
client_socket .send(f)
print ("Data Sent")
The Error
ERROR:Traceback (most recent call last):
File "tenmay.py", line 5, in <module>
client_socket.connect(("192.168.1.4", 8000))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
Send the contents of the file not the filehandle:
f=open ("TextFile", 'rb')
client_socket.send(f.read())
The second time the client runs the server is waiting to recv data because the accept() command is outside of the loop.
The client could repeatedly send data from a loop, but not if the program ends and has to be restarted.

Python socket (Socket Error Bad File Descriptor)

The following receiveFile() function reads a filename and file data from the socket and splits it using the delimiter $.
But I am unable to close the socket and a Bad file descriptor error is raised. If I comment out the self.server_socket.close() statement then there is no error but the socket is listening forever.
Code:-
def listen(self):
self.server_socket.listen(10)
while True:
client_socket, address = self.server_socket.accept()
print 'connected to', address
self.receiveFile(client_socket)
def receiveFile(self,sock):
data = sock.recv(1024)
data = data.split("$");
print 'filename', data[0]
f = open(data[0], "wb")
#data = sock.recv(1024)
print 'the data is', data[1]
f.write(data[1])
data = sock.recv(1024)
while (data):
f.write(data)
data=sock.recv(1024)
f.close()
self.server_socket.close()
print 'the data is', data
print "File Downloaded"
Traceback:-
Traceback (most recent call last):
File "server.py", line 45, in <module>
a = Server(1111)
File "server.py", line 15, in __init__
self.listen()
File "server.py", line 20, in listen
client_socket, address = self.server_socket.accept()
File "c:\Python27\lib\socket.py", line 202, in accept
sock, addr = self._sock.accept()
File "c:\Python27\lib\socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor
You are closing the server's listening socket, and after that calling again accept() on it.
To finish receiving one file you should close client connection's socket (sock in function receiveFile).
in this code i am trying to shut down the server once file is received
What you'll need is something to break out of the while True loop when you want to shut down the server. A simple solution would be to exploit the exception generated when you close the server socket...
def listen(self):
self.server_socket.listen(10)
while True:
try:
client_socket, address = self.server_socket.accept()
except socket.error:
break
print 'connected to', address
self.receiveFile(client_socket)
print 'shutting down'

Categories