I have a remote device which sends text data on TCP 5005 port. The code below is to get the data from remote device but its throwing an error. Can someone please help on this.
conn, addr = s.accept()
File "C:\Python26\lib\socket.py", line 197, in accept
sock, addr = self._sock.accept()
socket.error: [Errno 10022] An invalid argument was supplied"
Code:
#!/usr/bin/env python
import socket
TCP_IP = '192.168.0.12'
TCP_PORT = 5005
BUFFER_SIZE = 1024 # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
conn, addr = s.accept()
print 'Connection address:', addr
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print "received data:", data
conn.send(data) # echo
conn.close()
Related
I have a simple echo server that echos back whatever it receives. This works well for a single client request.
# echo-server.py
import socket
HOST = "127.0.0.1"
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print(f"Connected by {addr}")
while True:
try:
data = conn.recv(1024)
except KeyboardInterrupt:
print ("KeyboardInterrupt exception captured")
exit(0)
conn.sendall(data)
# echo-client.py
import socket
HOST = "127.0.0.1" # The server's hostname or IP address
PORT = 65432 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b"Hello, world")
data = s.recv(1024)
print(f"Received {data!r}")
However, if I finish one client request, and do a second client request, the server no more echoes back. How can I solve this issue?
(base) root#40029e6c3f36:/mnt/pwd# python echo-client.py
Received b'Hello, world'
(base) root#40029e6c3f36:/mnt/pwd# python echo-client.py
On the server side, you need to accept connections in an infinite loop. This should work.
server.py
HOST = "127.0.0.1"
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
while True:
conn, addr = s.accept()
print(f"Connected by {addr}")
try:
data = conn.recv(1024)
except KeyboardInterrupt:
print ("KeyboardInterrupt exception captured")
exit(0)
conn.sendall(data)
From client I am trying to send a txt file to server.
client.py
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 8340
BUFFER_SIZE = 1024
server_addr = (TCP_IP, TCP_PORT)
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.connect(server_addr)
file = open(r"C:\Users\sakthi\Desktop\Hi.txt",'r')
transfer = file.read(BUFFER_SIZE)
while transfer:
c.send(transfer.encode())
transfer = file.read(1024)
print (s.recv(BUFFER_SIZE).decode())
c.close()
Server.py
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 8340
BUFFER_SIZE = 1024 # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
final = open(r"C:\Users\sakthi\Desktop\final.txt", 'a+')
while 1:
print('Connection address:', addr)
r = conn.recv(BUFFER_SIZE).decode()
if not r:break
final.write(r)
print("received data:", r)
k="file received"
conn.send(k.encode())
conn.close()
Once the file is received, server will send message "file received" to client.
Client will print the message "file received" and close the connection
When I run the code, server.py is not coming out of while loop
while 1:
print('Connection address:', addr)
r = conn.recv(BUFFER_SIZE).decode()
if not r:break
final.write(r)
print("received data:", r)
r = conn.recv(BUFFER_SIZE).decode() keeps listening for new messages, but the client has transferred all messages.
size of the file is 1.14 KB.
Can anybody tell me what's wrong in my program?
I found the solution
Note our statement that recv() blocks until either there is data available to be read or the sender has closed the connection holds only if the socket is in blocking mode. That mode is the default, but we can change a socket to nonblocking mode by calling setblocking() with argument 0.
I have modified the server.py
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 8340
BUFFER_SIZE = 1024 # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
conn.setblocking(0)
final = open(r"C:\Users\sakthi\Desktop\final.txt", 'a+')
while 1:
try:
print('Connection address:', addr)
r = conn.recv(BUFFER_SIZE).decode()
final.write(r)
print("received data:", r)
except:
break
k="file received"
conn.send(k.encode())
conn.close()
Now I am able to receive the file and send message "file received" to client and connection is closed.
non-blocking socket,error is always
http://www.mws.cz/files/PyNet.pdf
I am basically trying to make a chatting app but here I am unable to send anything from the server to the client. How do I correct this?
server program:
from socket import *
host=gethostname()
port=7777
s=socket()
s.bind((host, port))
s.listen(5)
print "Server is Ready!"
while True:
c, addr= s.accept()
print c
print addr
while True:
print c.recv(1024)
s.sendto("Received",addr)
s.close()
client program:
from socket import *
host=gethostname()
port=7777
s=socket()
s.connect((host, port))
while True:
s.send(( raw_input()))
prin s.recv(1024)
s.close()
It is giving me error at s.sendto in server program saying:
File "rserver.py", line 14, in <module>
s.sendto("Received",addr)
socket.error: [Errno 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
You cannot use the connection socket to send or receive objects so the problem is there only....
Use -
c.sendto("Received", addr)
instead of
s.sendto("received", addr)
Second problem is you are not receiving the messages from the socket... Here is the working code
server.py -
from socket import *
host=gethostname()
port=7777
s=socket()
s.bind((host, port))
s.listen(5)
print "Server is Ready!"
while True:
c, addr= s.accept()
print c
print addr
while True:
print c.recv(1024)
#using the client socket and make sure its inside the loop
c.sendto("Received", addr)
s.close()
client.py
from socket import *
host=gethostname()
port=7777
s=socket()
s.connect((host, port))
while True:
s.send(( raw_input()))
#receive the data
data = s.recv(1024)
if data:
print data
s.close()
I want to know the Exception name that happen when a server have connection with a client in specific port, and another client wanna make a connection to server from that port ...
So i make server, client1 and client2 but when server and client1 are connected together and i run client3 amazingly without any error they all continue running.
I wanto to know why i didn`t get any error?
what's exactly the role of '1' in this line: serverSocket.listen(1)
This is server code:
import socket
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.bind(('', 80))
print("Host=%s" %str(serverSocket.getsockname()))
serverSocket.listen(1)
clientSocket, addr = serverSocket.accept()
print("Got a connection from %s" % str(addr))
data = clientSocket.recv(1024)
print("from Client:%s "%str(addr))
print("\n data:%s "%str(data.decode("utf-8")))
#consciously i didn't close the the sockets
client1:
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 80
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(bytes("test code", 'utf-8'))
data = s.recv(BUFFER_SIZE)
print(type(data))
s.close()
client2
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 80
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(bytes("test3", 'utf-8'))
data = s.recv(BUFFER_SIZE)
print(type(data))
s.close()
sth else,why when i run client2, the server didn`t show any message that got connection from it, like:
Got a connection from ('127.0.0.1', 64358)
The code of client1 fails with error:
TypeError: str() takes at most 1 argument (2 given)
It's because that bytes in python 2 is the same as str and it accepts only one string argument, credit goes to alecxe.
Im writing a simple socket program to receive some data and reverse the contents.
When I pass the reversed contents its not being sent..
Server
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print('Got connection from', addr)
print('Received message == ',c.recv(50))
s = c.recv(50)[::-1]
c.send(s)
c.close()
client
import socket
from time import sleep
s = socket.socket()
host = socket.gethostname()
port = 1234
s.connect((host, port))
print "Sending data"
s.sendall("Hello!! How are you")
print(s.recv(1024))
The problem is two lines in your server
Your server calls recv() inside a print statement. This empties the buffer. Then you call recv() again, but it is already emptied by the previous statement and so it then blocks.
You need to call recv() and store that in s. Then use s everywhere else.
Try this for your server:
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print('Got connection from', addr)
s = c.recv(50)
print('Received message == ',s)
c.send(s)
c.close()