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.
Related
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.
I got this error with python's tcp socket
Traceback (most recent call last): File "servidor_tcp_python.py",
line 205, in
ejecucion_servidor() File "servidor_tcp_python.py", line 27, in ejecucion_servidor
data = connection.recv(10000) ConnectionResetError: [Errno 104] Connection reset by peer
#Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('x.x.x.x', 10000)
print('starting up on %s port %s' % server_address)
sock.bind(server_address)
sock.listen(25)
while True:
# Wait for a connection
print ('waiting for a connection')
try:
connection, client_address = sock.accept()
print('connection from', client_address)
# Receive the data in small chunks and retransmit it
while True:
#with decode we convert byte to string, default decode is utf-8
data = connection.recv(10000)
print("Datos recibidos sin decodificar: "+str(data))
try:
data=data.decode("utf-8")
print("Datos recibidos decodificados: "+data)
#
#...... #
except UnicodeDecodeError:
break
except ConnectionResetError:
break
As you can see, I handle and catch the exception with the line
except ConnectionResetError:
break
But it is not working. Why? Should I close the connection after the except?
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.
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)
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'