Python indentation error after try: - python

I have a problem, whenever I try to run this python script on an Raspberry PI:
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 10000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(16)
print >>sys.stderr, 'received "%s"' % data
if data:
print >>sys.stderr, 'sending data back to the client'
connection.sendall(data)
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
I get this error:
File "server.py", line 20
try:
^
IndentationError: unexpected indent
Could you please tell me what's wrong here? The script is supposed to create a simple TCP/IP server, and I have no such problems with the client, so I really don't understand where is my mistake/s...

One of the unfortunate side-effects of Python's use of whitespace for denoting blocks is that sometimes you get scripts that have tabs and spaces mixed up throughout the source code.
Since this script is pretty small, you could try deleting the whitespace preceding each line's code and then reindent it properly.

Related

socket.accept() invalid argument

I was trying to create an easy client/server program with the module socket. it is the basic tutorial for every standard socket implementation.
#Some Error in sock.accept (line 13) --> no fix yet
import socket
import sys
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
print >>sys.stderr, 'starting up on %s' % host
serversocket.bind((host, 9999))
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#listening for incoming connections
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection , client_address = serversocket.accept()
try:
print >>sys.stderr, 'connection from', client_address
#Receive data in small chunks and retransmit it
while True:
data = connection.recv(16)
print >>sys.stderr,'received "%s"' % data
if data:
print >>sys.stderr, 'sending data back to the client'
connection.sendall(data)
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
#Clean up the connection
#Will be executed everytime
connection.close()
The output it gives is
C:\Python27\python27.exe C:/Users/Marcel/Desktop/Projekte/Python/Sockets/Socket_Test/server.py
starting up on Marcel-HP
waiting for a connection
Traceback (most recent call last):
File "C:/Users/Marcel/Desktop/Projekte/Python/Sockets/Socket_Test/server.py", line 16, in <module>
connection , client_address = serversocket.accept()
File "C:\Python27\lib\socket.py", line 206, in accept
sock, addr = self._sock.accept()
socket.error: [Errno 10022] Ein ung�ltiges Argument wurde angegeben
Before accepting any connections, you should start to [listen()][1] to new connections.
Here is the basic example from python documentation :
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Creation of the socket
s.bind((HOST, PORT)) # We tell OS on which address/port we will listen
s.listen(1) # We ask OS to start listening on this port, with the number of pending/waiting connection you'll allow
conn, addr = s.accept() # Then, accept a new connection
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
So, in your case, you only miss a serversocket.listen(1)right after the or serversocket.setsockopt(...)

Python closing sockets at random it seems

I've been looking and dealing with this issue for a week. I have client code that causes select() to return a socket that has actually closed from external reasons throwing an error 9 BAD FILE DESCRIPTOR, however I tested the code from a different python file and CANNOT get it to error. Ive tried a million things. heres a snippet from the server:
NOTE: This will work for a few iterations and then suddenly break, it errors out in the message_queue as key error due to the file descriptor breaking even tho a message/no message has a key for that socket present.
#Create the socket to communicate with uWSGI applications
server_address = ('localhost', 10001)
server = create_server_socket(server_address)
#Sockets which we expect to read on from select()
input_sockets = [server]
#Sockets which we expect to write to from select()
output_sockets = []
#Message buffer dicitonary for outgoing messages
message_queue = {}
#Now wait for connections endlessly
while input_sockets:
print >> sys.stderr, "Waiting for the next event..."
readable, writable, exceptional = select.select(input_sockets, output_sockets, input_sockets)
#Handle input_sockets
for s in readable:
#Server socket is available for reading now
if s is server:
#Create a connection and address object when incoming request is recieved
connection, client_addr = s.accept()
print >> sys.stderr, "Connection recieved from %s!" % (client_addr,)
#Set client connection to non blocking as well
connection.setblocking(0)
#Add this socket to input sockets as it will read for client data
input_sockets.append(connection)
#Give connection a queue for sending messages to it
message_queue[connection] = Queue.Queue()
#A client has sent data so we can handle its request
else:
#Pull data from the client
data = ""
try:
while True:
message = s.recv(1024)
if not message:
break
data += message
except Exception as e:
print str(e)
if data:
#Readable client socket has data
print >> sys.stderr, 'Recieved "%s" from %s' % (data, s.getpeername())
message_queue[s].put(data)
#Add output channel now to send message
if s not in output_sockets:
output_sockets.append(s)
#There is no data to be read, socket must be closed
else:
print >> sys.stderr, 'Closing', client_addr,'after recieving no data.'
#Stop listening for input on the socket
if s in output_sockets:
output_sockets.remove(s)
input_sockets.remove(s)
#Close the connection
s.close()
del message_queue[s]
#Handle writable connections
for s in writable:
if s:
try:
next_message = message_queue[s].get_nowait()
except:
print >> sys.stderr, 'No data to send for', s.getpeername()
output_sockets.remove(s)
else:
try:
print >> sys.stderr, 'Sending "%s" to %s' % (next_message, s.getpeername())
s.sendall(next_message)
except:
print >> sys.stderr, 'No data to send for', s.getpeername()
output_sockets.remove(s)
#s.sendall('EOF:!##$:EOF')
#Now handle any exceptions
for s in exceptional:
print >> sys.stderr, 'Handling exception on ', s.getpeername()
input_sockets.remove(s)
if s in output_sockets:
output_sockets.remove(s)
s.close()
#Remove any messages
del message_queue[s]
client:
messages = [ 'This is the message. ',
'It will be sent ',
'in parts.',
]
server_address = ('localhost', 10001)
# Create a TCP/IP socket
socks = [ socket.socket(socket.AF_INET, socket.SOCK_STREAM),
socket.socket(socket.AF_INET, socket.SOCK_STREAM),
]
# Connect the socket to the port where the server is listening
print >>sys.stderr, 'connecting to %s port %s' % server_address
for s in socks:
s.connect(server_address)
for message in messages:
# Send messages on both sockets
for s in socks:
print >>sys.stderr, '%s: sending "%s"' % (s.getsockname(), message)
s.send(message)
# Read responses on both sockets
for s in socks:
data = s.recv(1024)
print >>sys.stderr, '%s: received "%s"' % (s.getsockname(), data)
if not data:
print >>sys.stderr, 'closing socket', s.getsockname()
s.close()
NOTE: This client side is only to test and start passing messages.
There is a race in your code when a socket is returned as both readable and writable and you close the socket because the read returned 0 bytes. In this case you remove the socket from input_sockets, output_sockets and message_queue but the closed socket is still in writable and it will thus try to write to it inside the same iteration of the select loop.
I have no idea if this is the race you'll see because you neither show debug output not did you say where you stumble over this EBADF. To track similar problems down I recommend to augment your code with more debug information on where you close a socket and where you try to process a socket because it is readable or writable so that you actually find the exact place of the race when looking at the debug output.

Socket waiting for connection timeout

I'm trying to implement a timeout that terminates a python script when no connections are receiving for a defined time interval. So far I manage to implement the timeout using the following code:
import sys
import socket
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('192.168.43.112', 5001)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
try:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(16)
print >>sys.stderr, 'received "%s"' % data
if data:
print >>sys.stderr, 'Do stuff here'
else:
print >>sys.stderr, 'no more data from', client_address
sock.settimeout(5)
break
finally:
# Clean up the connection
connection.close()
except socket.timeout:
break
The code is working correctly in the sense that after establishing a connection and ending that very same connection, after 5 seconds the script terminates. However, if during the timeout window I try to make another connection I have the following error:
starting up on 192.168.43.112 port 5001
waiting for a connection
connection from ('192.168.43.1', 47550)
received "Data 0
"
Do stuff here
received ""
no more data from ('192.168.43.1', 47550)
waiting for a connection
connection from ('192.168.43.1', 39010)
---------------------------------------------------------------------------
error Traceback (most recent call last)
/Users/location/Desktop/sandbox/data_fetcher.py in <module>()
24 # Receive the data in small chunks and retransmit it
25 while True:
---> 26 data = connection.recv(16)
27 print >>sys.stderr, 'received "%s"' % data
28 if data:
error: [Errno 35] Resource temporarily unavailable
I'm not entirely sure how you want this all to work, and I find it a bit surprising that it happens this way right now (I didn't expect the timeout to have this effect), but based on the EAGAIN error (errno 35), what's happening is that the timeout on the main socket—which gets set only once you've had a first connection—is causing the second-accepted socket to be in non-blocking mode as well. This means that when you call connection.recv and there's no data immediately, you get that OSError raised.
I suspect some of this might vary a bit between OSes, but I was able to reproduces this on FreeBSD (you're probably running on Linux).
A minimal change that works around it—I don't think this is necessarily the best way to code this, but it does work—is to explicitly set the accepted socket to blocking:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = sock.accept()
connection.setblocking(1)
With this, the code behaves much better (I added a small test framework that spins off your code as a separate process, then makes several connections with varying delays).

Python - Simple TCP/IP S/C: Not all strings converted error for a print statement

Okay so i was setting up a simple socket TCP/IP server and client, and now i'm getting this error in, PyDev, inside Aptana Atudio 3. Server runs fine and waits for connection, but my client when ran give me the error
print 'establishing connection to server at %s ' % server_address
TypeError: not all arguments converted during string formatting
Ive gone to my normal resource before stack for trying to problem solve myself, and compared my code with the articles at PYMOTW and adjusted to match theirs and see if it changed my errors. I cant seem to see whats causing the error. I have my interpreter set to the same language of python as my pc is running... Heres my code,i've searched questions asked by other users with the same issue, but it always seems theres a fix for theirs that isnt working for me..
import socket
import sys
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # #UndefinedVariable
server_address = ('localhost', 0)
print 'establishing connection to server at %s' % server_address
sock.connect(input(server_address)) # #UndefinedVariable
try:
message = 'message to server'
print 'sending %s' % message
sock.sendall(message)
amount_recieved = 0
amount_expected = len(message) # #UndefinedVariable
while amount_recieved < amount_expected:
data = sock.recv(16)
amount_recieved += len(data) # #UndefinedVariable
print 'recieved %s' %(data)
finally:
print 'closing down'
sock.close
()
server_address is a tuple. Try this:
print 'establishing connection to server at %s ' % str(server_address)
or this:
print 'establishing connection to server at %s:%d ' % server_address

Data not received by twisted socket connection

I have a twisted server script listening on a unix socket and it receives the data when the client is in twisted but it doesn't work if i send it via a vanilla python socket code.
class SendProtocol(LineReceiver):
"""
This works
"""
def connectionMade(self):
print 'sending log'
self.sendLine(self.factory.logMessage)
if __name__ == '__main__':
address = FilePath('/tmp/test.sock')
startLogging(sys.stdout)
clientFactory = ClientFactory()
clientFactory.logMessage = 'Dfgas35||This is a message from server'
clientFactory.protocol = SendProtocol
port = reactor.connectUNIX(address.path, clientFactory)
reactor.run()
But this doesn't (server doesn't get any data)
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock_addr = '/tmp/test.sock'
try:
sock.connect(sock_addr)
except socket.error, msg:
print >> sys.stderr, msg
sys.exit(1)
sock.setblocking(0) # not needed though tried both ways
print 'connected %s' % sock.getpeername()
print 'End END to abort'
while True:
try:
line = raw_input('Enter mesg: ')
if line.strip() == 'END':
break
line += '\n'
print 'sending'
sock.sendall(line)
finally:
sock.close()
Your two client programs send different data. One sends \r\n-terminated lines. The other sends \n-terminated lines. Perhaps your server is expecting \r\n-terminated lines and this is why the latter example doesn't appear to work. Your non-Twisted example also closes the socket after the first line it sends but continues with its read-send loop.

Categories

Resources