socket question: ConnectionResetError: [Errno 54] Connection reset by peer - python

I am writing a simple socket app, and I have met this message and don't know how to fix it.
server_input =s.recv(1024)
ConnectionResetError: [Errno 54] Connection reset by peer
server.py
import socket
def main():
s = socket.socket()
port = 58257
client_address = "localhost"
s.bind((client_address, port))
s.listen(2)
user_input = input("Enter a message: ")
s.send(user_input.encode())
s.close()
if __name__ == '__main__':
main()
client.py
import socket
def main():
s = socket.socket()
#host = socket.gethostname()
port = 58257
client_address = "localhost"
s.connect((client_address, port))
print("connet ")
server_input =s.recv(1024)
server_input.decode()
print("Received message: " + server_input)
s.close()
if __name__ == '__main__':
main()
It is there any problem with my code? Thank you so much!!!

s.bind((client_address, port))
s.listen(2)
user_input = input("Enter a message: ")
s.send(user_input.encode())
The server needs to call accept on the server socket to get a socket for the connected client, then call send on this connected socket, not on the server socket.
Without this the connect in the client will still succeed, since it is done by the OS kernel on the server side. But since the connected socket is never accepted by the server it will be reset, thus resulting in the error you see.
So a more correct code on the server side would be
...
s.listen(2)
c,_ = s.accept()
user_input = input("Enter a message: ")
c.send(user_input.encode())
c.close()
Note that your client code has also other problems, i.e it should be
print("Received message: " + server_input.decode())

Related

Getting error non-blocking (10035) error when trying to connect to server

I am trying to simply send a list from one computer to another.
I have my server set up on one computer, where the IP address is 192.168.0.101
The code for the server:
import socket
import pickle
import time
import errno
HEADERSIZE = 20
HOST = socket.gethostbyname(socket.gethostname())
PORT = 65432
print(HOST)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(10)
while True:
conn, adrs = s.accept()
print(f"Connection with {adrs} has been established")
conn.setblocking(1)
try:
data = conn.recv(HEADERSIZE)
if not data:
print("connection closed")
conn.close()
break
else:
print("Received %d bytes: '%s'" % (len(data), pickle.loads(data)))
except socket.error as e:
if e.args[0] == errno.EWOULDBLOCK:
print('EWOULDBLOCK')
time.sleep(1) # short delay, no tight loops
else:
print(e)
break
The client is on another computer. The code:
import socket
import pickle
HOST = '192.168.0.101'
PORT = 65432
def send_data(list):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10)
print(".")
print(s.connect_ex((HOST, PORT)))
print(".")
data = pickle.dumps(list)
print(len(data))
s.send(data)
s.close()
send_data([1,1,1])
The outputted error number of connect_ex is 10035. I read a lot about the error, but all I found was about the server side. To me, it looks like the problem is with the client and that it is unable to make a connection to 192.168.0.101. But then, I don't understand why the error I get is about non-blocking.
What is it that I am doing wrong that I am unable to send data?
First of all, how user207421 suggested, change the timeout to a longer duration.
Also, as stated here Socket Programming in Python raising error socket.error:< [Errno 10060] A connection attempt failed I was trying to run my server and connect to a private IP address.
The fix is: on the server side, in the s.bind, to leave the host part empty
HOST = ''
PORT = 65432
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
And on the client side, use the public IP of the PC where the server is running (I got it from ip4.me)
HOST = 'THE PUBLIC IP' #not going to write it
PORT = 65432
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, PORT))

Python socket.error: [Errno 32] Broken pipe

i made a python listener(server) on my vps
but when i give the server and client the ip addreess of vps and port 8585
this error shows:
error :
socket.error: [Errno 32] Broken pipe
i use python version 2 in vps
i use python version 3 in my PC
my server code :
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ip = raw_input("ip : ")
ip = str(ip)
port = raw_input("port : ")
port = int(port)
s.bind((ip,port))
s.listen(5)
while True:
c, addr = s.accept()
s.send("welcome !")
print (addr, "connected.")`
client :
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
HOST = input("HOST : ")
HOST = str(HOST)
PORT = input("PORT : ")
PORT = int(PORT)
s.connect((HOST,PORT))
buff = 1024
data = s.recv(buff)
print(data)`
In the server you have:
c, addr = s.accept()
s.send("welcome !")
You must do the send on the connected socket to the client and not on the listener socket, i.e. it should be c.send instead of s.send.

Python: [WinError 10054] An existing connection was forcibly closed by the remote host

I'm creating a client to server based chat client and every time I setup a server and a client, the server keeps listening for a connection and when the client attempts to connect this error appears [WinError 10054] An existing connection was forcibly closed by the remote host, however the server still listens for a connection. I'm using python version 3.6.1
Script
import socket
import threading
clients = []
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
mode = input("Enter 1 for server mode and enter 2 for client mode")
if mode == "1":
def get_ip():
try:
stest = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
stest.connect(('10.255.255.255', 1))
IP = stest.getsockname()[0]
except:
IP = '127.0.0.1'
finally:
stest.close()
return IP
print("IP: " + get_ip())
s.bind((get_ip(), 7999))
s.setblocking(0)
print("Waiting for connection")
while True:
try:
data, addr = s.recvfrom(1024)
if data.decode() == "Quit":
quitmsg = str(addr) + " has quit the chat."
clients.remove(addr)
for client in clients:
s.sendto(quitmsg.encode("utf-8"), client)
break
elif data:
print(data)
if addr not in clients:
clients.append(addr)
print(clients[0])
for client in clients:
print(client)
s.sendto(data, client)
except:
pass
s.close()
elif mode == "2":
while True:
try:
ip = input("Enter in an ip address")
socket.inet_aton(ip)
except socket.error:
print("Invalid IPv4 address")
continue
while True:
try:
port = int(input("Enter in port number"))
except ValueError:
print("Invalid Port Number")
continue
break
addr = (ip, port)
break
s.connect(addr)
def recvmsg():
while True:
data = s.recv(1024)
print(data)
if data:
print(data.decode())
recv = threading.Thread(name="recvmsg", target=recvmsg)
recv.daemon = True
recv.start()
while True:
string = input(">>")
s.send(string.encode("utf-8"))
if str(string) == "Quit":
break
s.close()
print("Disconnected from chat")
Server Waiting For connection even after client can't connect
Client Failed to connect
If your server is not on the local network, make sure port 7999 is open and forwarded on its access point. Otherwise the packets will just be dropped by the router. If it is on your local network, still try forwarding. Also according to https://www.speedguide.net/port.php?port=7999 the port has been used by a worm, so maybe permanently closed on the other network?? Unlikely but possible.

Why doesn't my python socket connect to another computer?

So i've recently started testing out sockets and i have managed to create a server and client, which are both working together when i run them on the same pc. However, when i put in the server on a diffrent computer it gives me the following error: ""TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond""
Here is my server:
import socket
import pyautogui
import os
computerIP = socket.gethostbyname(socket.gethostname())
def Main():
host = computerIP
port = 5000
value = 0
mySocket = socket.socket()
mySocket.bind((host,port))
mySocket.listen(1)
conn, addr = mySocket.accept()
print ("Connection from: " + str(addr))
while True:
data = conn.recv(1024).decode()
if not data:
break
elif data == "shift":
pyautogui.keyDown("shift")
elif data == "relshift":
pyautogui.keyUp("shift")
elif data == "logout":
os.popen("shutdown -l")
elif data == "click":
pyautogui.click()
pyautogui.click()
print ("from connected user: " + str(data))
data = str(data).upper()
print ("sending: " + str(data))
conn.send(data.encode())
conn.close()
if __name__ == '__main__':
Main()
My client:
import socket
def Main():
host = #same ip as server
port = 5000
mySocket = socket.socket()
mySocket.connect((host,port))
message = input(" -> ")
while message != 'q':
mySocket.send(message.encode())
data = mySocket.recv(1024).decode()
print ('Received from server: ' + data)
message = input(" -> ")
mySocket.close()
if __name__ == '__main__':
Main()
OS: Windows 8.1
Python verion: 3.4
I tried looking this up on the internet but since i'm pretty new to python i didn't understand much.
Tell me if there is anything i need to clearify.
Looks like the port is blocked due to some firewall.
Use socket.connect_ex() instead of socket.connect(). If the connection succeeds it would return 0, otherwise the value of the errno variable will help you debug why the connection failed.
Prior to the connection also use socket.settimeout() so that the connection times out in the given no. of seconds.

Socket Python Exchange

I am trying to build a TCP Chat Program that is multithreaded. So far I think most of the functions are setup fine. When starting the server and connecting with a client only responses sent from the server are broadcasted to all clients connected. I think I figured out why that is and it comes from the CONNECTION_LIST array I have. The server appends all clients to this list and I thought I had the same thing going for the clients but the client instance never sees this list so when sending messages they messages aren't sent anywhere. I basically need a way to copy the CONNECTION_list from the server instance over to the connected clients. I been trying figure out how to possibly do this all day and its driving me crazy.
import socket
import platform
import threading
import sys
import time
import os
'''Define Globals'''
HOST = ""
PORT = 25000
ADDR = (HOST, PORT)
CONNECTION_LIST = []
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
'''Connect Client to the Server'''
def client_connect():
server_ip = input("[+] Server's IP to connect to: ")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect((server_ip, PORT))
print("[+] Connected to Server at address: %s" %client.getpeername()[0])
except ConnectionRefusedError:
print("[*] No Server Listening at Specified Address")
sys.exit()
communicate(client)
'''Threaded loop to continue listening for new connections'''
def server_loop():
server.bind(ADDR)
server.listen(10)
print("[*] Server started on %s" %platform.node())
while True:
client_socket, client_addr = server.accept()
CONNECTION_LIST.append(client_socket)
print("\r[+] New Connection from: %s" %client_addr[0])
'''Broadcast data to all clients except sender'''
def broadcast_data(sock, message):
for socket in CONNECTION_LIST:
if socket != server and socket != sock:
try:
socket.send(str.encode("[%s] => %s" %(os.getlogin(),message)))
except:
socket.close()
CONNECTION_LIST.remove(socket)
'''Server Host Connect Back'''
def self_connect():
sc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sc.connect(("localhost", 25000))
CONNECTION_LIST.append(sc)
communicate(sc)
def communicate(client):
dump_thread = threading.Thread(target=dump, args=(client,))
dump_thread.start()
while True:
try:
time.sleep(0.5)
data = input("> ")
broadcast_data(client, data)
except:
print("[*] Error - Program Terminating")
client.close()
sys.exit()
def dump(client):
while True:
print(client.recv(1024).decode("utf-8"))
def main():
server_thread = threading.Thread(target=server_loop)
while True:
try:
print("Select Operating Mode")
print("---------------------")
print("1. Server Mode")
print("2. Client Mode")
mode = int(input("Enter mode of operation: "))
print("\n\n")
if mode in [1,2]:
break
else:
raise ValueError
except ValueError:
print("Enter either (1) for Server or (2) for Client")
if mode == 1:
server_thread.start()
time.sleep(1)
self_connect()
elif mode == 2:
client_connect()
main()

Categories