Sockets in Python giving error - python

I am serving a test file as follows:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
facebook = open("sources/facebook.htm","rb")
listen = ("localhost", 2000)
sock.bind(listen)
sock.listen(1)
while True:
connection, client_address = sock.accept()
print("Got a Connection from: " + client_address[0])
sock.send(facebook.read(10000000))
I have downloaded facebook homepage to test connections but when I connect to this page, it gives the following error:
Got a Connection from: 127.0.0.1
Traceback (most recent call last):
File "C:\Users\Export.1\blocker.py", line 11, in
sock.send(facebook.read(1000000))
OSError: [WinError 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
How can I fix it?

The error occurs because you are sending reply to the server socket instead of client, try changing
sock.send(facebook.read(10000000))
to
connection.send (facebook.read(1000000))
instead

Related

Broken pipe error when trying to send data from server to client in Python sockets

I am trying to use "vanilla" Python sockets to transmit data from a server to a client, without using any asynchronous programming. My use case is the following: I would like a local Raspberry Pi to connect to my internet exposed server, and the server to send data through the created socket when a given event occurs.
I followed several tutorials on simple socket programming in Python to build the following code:
server.py
import socket
import time
def server():
PORT = 65432
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('0.0.0.0', PORT))
s.listen(1)
conn,address=s.accept() # accept an incoming connection using accept() method which will block until a new client connects
print("address: ", address[0])
time.sleep(5)
s.send("hey".encode())
conn.close()
return
server()
client.py
import socket
import time
HOST = "my.remote.domain"
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
while True :
print(s.recv(1024))
time.sleep(1)
When launching the server and the client on their respective machine, I can see that the connexion is correctly made, since the IP address of the client is printed in the logs of the server. However, after few seconds and before sending any data, I get the following error on the server side:
address: client_ip_address_appears_here
Traceback (most recent call last):
File "main.py", line 32, in <module>
receiver()
File "main.py", line 18, in receiver
s.send("heeey".encode())
BrokenPipeError: [Errno 32] Broken pipe
Meanwhile on the client side, no data is received:
b''
b''
b''
b''
b''
b''
b''
b''
b''
Is there a conceptual problem in the way I try to handle the socket ?
After trying out the code, I think the biggest problem you have is that the server is trying to send on the wrong socket. i.e. this line:
s.send("hey".encode())
should be rewritten like this:
conn.send("hey".encode())
As it is, you are trying to send() on the TCP accepting-socket rather than on the TCP connection to the client, which doesn't make sense. On my (MacOS/X) system, the server process prints this error output:
Jeremys-Mac-mini-2:~ jaf$ python server.py
('address: ', '127.0.0.1')
Traceback (most recent call last):
File "server.py", line 18, in <module>
server()
File "server.py", line 14, in server
s.send("hey".encode())
socket.error: [Errno 57] Socket is not connected

Python client refuses to connect to my SocketServer server

Hello,
I have a problem , I have a python server creates with SocketServer ( I learn ) , this one apparently works , but when I want to connect with my client I get a traceback , I really do not understand . Allow me to share code of the server, the client, telnet and traceback
server code:
import SocketServer
import threading
class EchoHandler(SocketServer.BaseRequestHandler):
def handle(self):
print "{} is connected".format(self.client_address)
data = "test"
while len(data):
data=self.request.recv(1024)
print "Client sent: {}".format(data)
self.request.send(data)
print "Client is gone"
server_Addr = "127.0.0.1"
server_port = 7008
print "Running Server on address {} and port {}".format(server_Addr,server_port)
server = SocketServer.ThreadingTCPServer((server_Addr,server_port), EchoHandler)
server.serve_forever()
client code:
#!/usr/bin/env python
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 7008
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()
print "received data:", data
the traceback:
Traceback (most recent call last):
File "/home/labofx/Bureau/client_script_v6.py", line 11, in <module>
s.connect((TCP_IP, TCP_PORT))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
error: [Errno 111] Connection refused
the telnet output to show that the server is working
labofx#labofx-To-be-filled-by-O-E-M:~$ telnet 127.0.0.1 7008 Trying 127.0.0.1... Connected to 127.0.0.1. Escape character is '^]'. hello hello
and the output of the server:
Running Server on address 127.0.0.1 and port 7008 ('127.0.0.1', 50825) is connected Client sent: hello
PS: sorry for my bad English I am native French speaking
Thank you in advance for your assistance
thank you Chaker ^^
With your comment ,I have found how to make it work. The client need to be executed through the terminal, the error comes only when i run it through the file with run module.

Getting error while binding a socket

I am scripting a server to use at many things, gaming, data-transfer, chatting etc.
My problem is i am getting this error:
Traceback (most recent call last):
File "server.py", line 11, in <module>
s.bind((host, port))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
TypeError: an integer is required
I am at the beginning of my server script so far and i scripted many networking scripts before. There shouldnt be any problem. I tried this script both on my local and on my servers and still same resuly and the exact same error. I will really appreciate any kind of help.
Here is my code:
#!/usr/bin/python
# This is server file
import socket
# server & connection settings
host = '127.0.0.1'
port = '5002'
s = socket.socket() # Creating socket object
s.bind((host, port))
s.listen(10)
# server & connection settings
while True:
c,addr = s.accept() # Establish connection with clients.
print 'Got connection from ', addr # Print ip adress of the recently connected client.
c.send('You succesfully established connection with our servers.') # Send socket to the client.
print 'Socket had been sent to the client: ', addr # Print to the server console that we succesfully established connection with the client
c.close() # Close the client connection. Bye, bye! /// Will delete this part when the time come

socket.error: [Errno 111] when trying to connect to a socket

I was trying to write a code where a client connects to server on a default port number, the server then sends another port number to the client. The client now connects to the new port number.
Client:
import socket
import sys
import os
import signal
import time
s = socket.socket()
s.connect(("127.0.0.1", 6667))
line = s.recv(1024)
if line.strip():
port = int(line)
s.close()
soc = socket.socket()
soc.connect(("127.0.0.1", port))
print soc.recv(1024)
soc.close()
else:
s.close()
Server:
import socket
import sys
import os
import signal
import time
port = 7777
s = socket.socket()
s.bind(("127.0.0.1", 6667))
s.listen(0)
sc, address = s.accept()
print address
sc.send(str(port))
sc.close()
s.close()
sock = socket.socket()
sock.bind(("127.0.0.1", port))
soc, addr = sock.accept()
print addr
soc.send("Success")
soc.close()
sock.close()
When I execute this code, I am getting following errors on client and server sides.
Server:
('127.0.0.1', 36282)
Traceback (most recent call last):
File "server.py", line 17, in <module>
soc, addr = sock.accept()
File "/usr/lib/python2.7/socket.py", line 202, in accept
sock, addr = self._sock.accept()
socket.error: [Errno 22] Invalid argument
Client:
Traceback (most recent call last):
File "client.py", line 13, in <module>
soc.connect(("127.0.0.1", port))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
Can someone explain me the reason for these errors and provide a solution for these errors.
Before you can listen to a TCP/IP socket (a connection based streaming socket) you need to use bind to assign a socket (created with socket.socket()) . Then you need to do listen to prepare it for incoming connections and then finally you do accept on the prepared socket.
You appear to be missing sock.listen(0) after your call to sock.bind(("127.0.0.1", port)). The Python documentation is short on details but it does say this about TCP/IP:
Note that a server must perform the sequence socket(), bind(), listen(), accept() (possibly repeating the accept() to service more than one client), while a client only needs the sequence socket(), connect(). Also note that the server does not sendall()/recv() on the socket it is listening on but on the new socket returned by accept().
Python bases its socket module on a Berkeley Socket model. You can find some more detailed information on Berkeley Sockets at this link . In particular it says this about bind:
bind() assigns a socket to an address. When a socket is created using socket(), it is only given a protocol family, but not assigned an address. This association with an address must be performed with the bind() system call before the socket can accept connections to other hosts.
Also consider what would happen if your client gets sent a port number (and tries to connect) before the server starts listening for connections (on port 7777 in this case). Although not the cause of your problems, I wanted to point out the scenario for completeness. Something you may consider is not closing the port 6667 socket until after you have called listen on the port 7777 socket. After calling listen you can then close down the first socket. On the client after reading the port you can wait until the first connection (port 6667) is closed down by the server and then connect to port 7777.

Server Client Communication Python

Server
import socket
import sys
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host= 'VAC01.VACLab.com'
port=int(2000)
s.bind((host,port))
s.listen(1)
conn,addr =s.accept()
data=s.recv(100000)
s.close
CLIENT
import socket
import sys
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host="VAC01.VACLab.com"
port=int(2000)
s.connect((host,port))
s.send(str.encode(sys.argv[1]))
s.close()
I want the server to receive the data that client sends.
I get the following error when i try this
CLIENT Side
Traceback (most recent call last):
File "Client.py", line 21, in
s.send(sys.argv[1])
TypeError: 'str' does not support the buffer interface
Server Side
File "Listener.py", line 23, in
data=s.recv(100000)
socket.error: [Errno 10057] A request to send or receive data was disallowed bec
ause the socket is not connected and (when sending on a datagram socket using a
sendto call) no address was supplied
In the server, you use the listening socket to receive data. It is only used to accept new connections.
change to this:
conn,addr =s.accept()
data=conn.recv(100000) # Read from newly accepted socket
conn.close()
s.close()
Your line s.send is expecting to receive a stream object. You are giving it a string. Wrap your string with BytesIO.
Which version of Python are you using? From the error message, I guess you are unintentionally using Python3. You could try your program with Python2 and it should be fine.
try to change the client socket to:
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

Categories