Python client refuses to connect to my SocketServer server - python

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.

Related

Python-Micropython TCP sockets on w5100s-EVB-Pico

I have a W5100S-EVB-Pico which is basically a Pi Pico with an ethernet port. I would like to send commands to it over a TCP socket connection. Basically I want to control hardware over ethernet using this board.
The W5100 board should be a server that accepts connections/commands.
I plan on programming a GUI in Python to send commands
I'm running this micropython version on it.
Python version 3.7
But this is the problem now: The code below keeps giving me this error: 'OSError: [Errno 107] ENOTCONN'
EDIT_01: It seems like I'm closing the connection too soon from the client side ()
EDIT_02: Do I need some kind of acknowledgement from the server before closing? Or, what are possible ways to implement this kind of communication?
Thanks for reading!
Here's the code and an explanation of what's going on:
The code on the W5100-EVB-Pico:
from machine import Pin, SPI
import network
import usocket as socket
# Only needed for static IP setup:
ip_address = '192.168.1.20'
subnet = '255.255.255.0'
gateway = '192.168.1.1'
dns = '8.8.8.8'
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_port = 8080
# Init ethernet
def init_ethernet():
spi = SPI(0, 2_000_000, mosi=Pin(19), miso=Pin(16), sck=Pin(18))
nic = network.WIZNET5K(spi, Pin(17), Pin(20))
# Static IP:
# nic.ifconfig((ip_address, subnet, gateway, dns))
# DHCP:
nic.active(True)
while not nic.isconnected():
pass
ip_address = nic.ifconfig()[0]
subnet = nic.ifconfig()[1]
gateway = nic.ifconfig()[2]
dns = nic.ifconfig()[3]
print('Connected:')
print('IP ', ip_address)
print('Subnet ', subnet)
print('Gateway ', gateway)
print('DNS ', dns)
listen()
def listen():
server_socket.bind((ip_address, socket_port))
server_socket.listen(5)
print(f'Listening on {ip_address} port {socket_port}')
while True:
print('>>>This should print once and it does')
print('>>>Waiting for connection')
client, address = server_socket.accept()
print(f'Client connected from: {address}')
client.close()
if __name__ == "__main__":
init_ethernet()
The output when running this is:
netif changed 192.168.1.20
Connected:
IP 192.168.1.20
Subnet 255.255.255.0
Gateway 192.168.1.1
DNS 192.168.1.150
Listening on 192.168.1.20 port 8080
>>>This should print once and it does
>>>Waiting for connection
My Python code:
import socket
local_IP = socket.gethostbyname(socket.gethostname())
port = 8080
server_ip = '192.168.1.20'
server_port = 8080
server_address = (server_ip, server_port)
def test_socket():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect(server_address)
message = 'Hello from client'
s.sendall(bytes(message, encoding="utf-8"))
if __name__ == '__main__':
test_socket()
As soon as I run this code the output from the W5100 is:
...
>>>This should print once and it does
>>>Waiting for connection
Traceback (most recent call last):
File "<stdin>", line 55, in <module>
File "<stdin>", line 37, in init_ethernet
File "<stdin>", line 49, in listen
OSError: [Errno 107] ENOTCONN
=============================================
EDIT_01:
I found that when I add 'time.sleep(1)' here:
s.sendall(bytes(message, encoding="utf-8"))
time.sleep(1)
s.close()
The error does not occur. Am I closing the socket too soon on the Python side?
=============================================
EDIT_02:
I changed this code on the server:
while True:
print('>>>Waiting for connection')
client, address = server_socket.accept()
print(f'Client connected from: {address}')
data = client.recv(1024).decode()
print(data)
client.close()
And this on the client:
def test_socket():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(server_address)
message = 'This is a really long message of many bytes and can\n' \
'even be some very long JSON data?\n' \
'which is pretty awesome!\n' \
'Man This is what I was after !!!'
s.sendall(bytes(message, encoding="utf-8"))
time.sleep(1)
s.close()
However, time.sleep(1) is not the way to go :(
I think I should close the socket after an acknowledgement from the server?
Any hint and tips are welcome,
Thanks!
Ok, the key seems to be error catching in the communication.
This client code works like intended... for now.
import socket
import json
local_IP = socket.gethostbyname(socket.gethostname())
port = 8080
server_ip = '192.168.1.20'
server_port = 8080
server_address = (server_ip, server_port)
commands = [['A', 1, '1234567890_1234567890_1234567890'],
['B', 2, 'hello'],
['C', 3.7],
['D', 4]]
def test_socket():
for c in commands:
send(json.dumps(c))
def send(message):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(server_address)
s.sendall(bytes(message, encoding="utf-8"))
try:
received_data, addr = s.recvfrom(128)
print(received_data, addr)
print(received_data.decode('utf-8'))
except socket.error as error:
print(f'Socket error: {error.errno}')
finally:
pass
if __name__ == '__main__':
test_socket()

Cionnection Refused when running Python script

I am running the following python script within Oracle Virtualbox running Kali Linux and keep getting connection refused.
client.py
#!/usr/bin/python3
#client.py
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 8080
client.connect((host, port)) # Connect to our client
msg = client.recv(1024)
client.close()
print (msg.decode('ascii'))
┌──(kali㉿kali)-[~/Downloads]
└─$ python3 client.py
Traceback (most recent call last):
File "/home/kali/Downloads/client.py", line 10, in <module>
client.connect((host, port)) # Connect to our client
ConnectionRefusedError: [Errno 111] Connection refused
I have solved this, the code is correct but I have not created a listner on port 8080.
Create a new python file name server.py and ran it.
Then ran my client.py
#!/usr/bin/python3
#server.py
import socket
host = socket.gethostname()
port = 8080
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host,port))
server.listen(2)
print('Server is listening for incoming connections')
while True:
conn,addr = server.accept()
print("Connection Received from %s" % str(addr))
msg = 'Connection Established'+ "\r\n"
conn.send(msg.encode('ascii'))
conn.close()

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 Socket Programming - ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

I'm doing an assignment regarding socket programming in python using a client and server. I'm currently on windows 10. Before getting into the little details of the assignment, I've been trying to simply connect the server and client.
Every time I try to run the client file, I would get this error
File "tcpclient.py", line 9, in <module>
s.connect((host, port))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
I have opened the firewall ports and still nothing. I've tried replacing host with '', 0.0.0.0, socket.gethostname() in both the client and server file but the error still persists. I've even tried different port numbers but it made no difference. I've tried running this code on Ubuntu and Max and I get the same error - connection refused. I've been researching for many solutions but I still have yet to find one that works. Any help would be greatly appreciated!
Note: this code was taken online but it's essentially the basis of what I need to accomplish.
tcpclient.py
import socket
host = '127.0.0.1'
port = 80
buffer_size = 1024
text = "Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(text)
data = s.recv(buffer_size)
s.close()
print("received data:", data)
tcpserver.py
import socket
host = '127.0.0.1'
port = 80
buffer_size = 20
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
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()
Just use a different port. Both the client and server should have the same port and host if not it won't work. Make sure to run the server before the client script.
For client.py
import socket
host = '127.0.0.1'
port = 9879
buffer_size = 1024
text = "Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
text = text.encode('utf-8')
s.send(text)
data = s.recv(buffer_size)
s.close()
print("received data:", data)
For server.py
import socket
mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
buffer_size = 1024
text = "Hello, World!"
mysocket.bind(('127.0.0.1', 9879))
mysocket.listen(5)
(client, (ip,port)) = mysocket.accept()
print(client, port)
client.send(b"knock knock knock, I'm the server")
data = client.recv(buffer_size)
print(data.decode())
mysocket.close()
Just change the port number and it will work and if you are in python3 then you will have to encode and decode as socket recieves and sends only binary strings.
I have succeed in my server!
My server python script is below:
import socket
host='0.0.0.0'
port=2345
s=socket.socket()
s.bind((host,port))
s.listen(2)
while True:
conn,addr=s.accept()
print("Connected by",addr)
data=conn.recv(1024)
print("received data:",data)
conn.send(data)
conn.close()
My Client python script is below:
import socket
s=socket.socket()
host="xx.xx.xx.xx" #This is your Server IP!
port=2345
s.connect((host,port))
s.send(b"hello")
rece=s.recv(1024)
print("Received",rece)
s.close()
There is two points needed to be careful in the script:
1.The host of the Server must is
'0.0.0.0'
So that the python script could user all interfaces in the server
2.I have find the question's error through the prompt:
TypeError: a bytes-like object is required, not 'str'
It means every string message in the 'send' method need to convert to 'bytes-like object',So the correct is
s.send(b"hello")
It is important that this is b'hello' not is 'hello'
I was following a tutorial that used threading to start the server. Once I removed the threading then I was able to connect to it.

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

Categories