socket python library. client crashes - python

I start the server, then the client, the server gets the data and the client does not get a response, crashes
server
import pygame, socket, time
pygame.init()
main_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
main_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
main_socket.bind(("localhost", 10000))
main_socket.setblocking(0)
main_socket.listen(5)
players_sockets = []
while True:
try:
new_socket, addr = main_socket.accept()
print("Connect", addr)
new_socket.setblocking(0)
players_sockets.append(new_socket)
except:
pass
for i in players_sockets:
try:
data = i.recv(1024)
data = data.decode()
except:
pass
for i in players_sockets:
try:
i.send("server data").encode()
except:
players_sockets.remove(i)
print("Disconnect")
i.close()
time.sleep(1)
client
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.connect(("localhost", 10000))
while True:
sock.send("Command".encode())
data = sock.recv(1024)
data = data.decode()
print(data)
error:
" data = sock.recv(1024)
ConnectionAbortedError: [WinError 10053] The program on your host computer has broken an established connection."

Related

Socket Error Python

I had the following code and I cannot observe the behaivour of server and receiver client because client sender pops error continiously. How can I handle this?
Error: An existing connection is forced to shut down by a remote computer
Client Sender
import socket
import sys
serverName = 'localhost'
serverPort = 12000
while True:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((serverName, serverPort))
f = open("sentfile.txt")
l = f.read(2097152)
while(l):
l_bytes = bytes(l, "utf-8")
s.sendall(l_bytes)
Server
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('localhost', 12000))
s.listen(1)
print ("The server is ready")
conn, addr = s.accept()
with conn:
print('Connected by ', addr)
while True:
data = conn.recv(2097152)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as p:
p.bind(('localhost', 1000))
conn2, addr2 = p.accept()
with conn2:
conn2.sendall(data)
Client Receiver
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('localhost', 1000))
s.listen(1)
conn, addr = s.accept()
with conn:
while True:
f = open('receivedfile.txt', 'ba')
data = connRev(2097152)
f.write(data)
f.close()
first you have to import Socket module. Then use the function getaddrinfo().

Server Loop Using Python Sockets and Threading module

I am making server-client communication in python using sockets and threading module. I connect client to server, send some data, receive some data, but the problem is, I can send only two messages. After those, the server is not reciving my packets. Can someone tell me what's wrong? Thanks in advance.
Server.py:
import socket
from threading import Thread
class Server:
def __init__(self):
self.host = '127.0.0.1'
self.port = 9999
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((self.host, self.port))
self.server.listen(5)
self.threads = []
self.listen_for_clients()
def listen_for_clients(self):
print('Listening...')
while True:
client, addr = self.server.accept()
print('Accepted Connection from: '+str(addr[0])+':'+str(addr[1]))
self.threads.append(Thread(target=self.handle_client, args=(client, addr)))
for thread in self.threads:
thread.start()
def handle_client(self, client_socket, address):
client_socket.send('Welcome to server'.encode())
size = 1024
while True:
message = client_socket.recv(size)
if message.decode() == 'q^':
print('Received request for exit from: '+str(address[0])+':'+str(address[1]))
break
else:
print('Received: '+message.decode()+' from: '+str(address[0])+':'+str(address[1]))
client_socket.send('Received request for exit. Deleted from server threads'.encode())
client_socket.close()
if __name__=="__main__":
main = Server()
Client.py
import socket
import sys, time
def main():
target_host = '127.0.0.1'
target_port = 9999
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print('Could not create a socket')
time.sleep(1)
sys.exit()
try:
client.connect((target_host, target_port))
except socket.error:
print('Could not connect to server')
time.sleep(1)
sys.exit()
while True:
data = input()
client.send(data.encode())
message = client.recv(4096)
print('[+] Received: '+ message.decode())
main()
You have to send exit message 'q^' to client too to close client.
Warning:
Using Unicode as encoding for string is not recommended in socket. A partial Unicode character may be received in server/client resulting in UnicodeDecodeError being raised.
Code for server using threads is:
server.py:
import socket
from threading import Thread
class Server:
def __init__(self, host, port):
self.host = host
self.port = port
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((self.host, self.port))
self.server.listen(5)
def listen_for_clients(self):
print('Listening...')
while True:
client, addr = self.server.accept()
print(
'Accepted Connection from: ' + str(addr[0]) + ':' + str(addr[1])
)
Thread(target=self.handle_client, args=(client, addr)).start()
def handle_client(self, client_socket, address):
size = 1024
while True:
try:
data = client_socket.recv(size)
if 'q^' in data.decode():
print('Received request for exit from: ' + str(
address[0]) + ':' + str(address[1]))
break
else:
# send getting after receiving from client
client_socket.sendall('Welcome to server'.encode())
print('Received: ' + data.decode() + ' from: ' + str(
address[0]) + ':' + str(address[1]))
except socket.error:
client_socket.close()
return False
client_socket.sendall(
'Received request for exit. Deleted from server threads'.encode()
)
# send quit message to client too
client_socket.sendall(
'q^'.encode()
)
client_socket.close()
if __name__ == "__main__":
host = '127.0.0.1'
port = 9999
main = Server(host, port)
# start listening for clients
main.listen_for_clients()
client.py:
import socket
import sys, time
def main():
target_host = '127.0.0.1'
target_port = 9999
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print('Could not create a socket')
time.sleep(1)
sys.exit()
try:
client.connect((target_host, target_port))
except socket.error:
print('Could not connect to server')
time.sleep(1)
sys.exit()
online = True
while online:
data = input()
client.sendall(data.encode())
while True:
message = client.recv(4096)
if 'q^' in message.decode():
client.close()
online = False
break
print('[+] Received: ' + message.decode())
break # stop receiving
# start client
main()

how to create a UDP server that will listen on multiple ports in python?

this is my server:
import socket
for port in range(33,128):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('0.0.0.0', port))
while True:
(client_name, client_adress) = server_socket.recvfrom(1024)
print chr(port)
server_socket.close()
this is my client:
import socket
message = raw_input("Enter a message: ")
for letter in message:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
my_socket.sendto("", ('127.0.0.1', ord(letter)))
(data, remote_adress) = my_socket.recvfrom(1024)
my_socket.close()
print 'The server sent: ' + data
I'm not very good in python, but I think you should save your sockets to list inside for and then use select function in infinite loop outside for
import socket
import select
sockets = []
for port in range(33,128):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('0.0.0.0', port))
sockets.append(server_socket)
empty = []
while True:
readable, writable, exceptional = select.select(sockets, empty, empty)
for s in readable:
(client_data, client_address) = s.recvfrom(1024)
print client_address, client_data
for s in sockets:
s.close()

Socket programing - constantly send and recive data (python)

I'm programing a very simple screen sharing program.
I have the code for sending and reciving the screen picture. I want the server to be able to recive data at any time, and I want the Client to send the data every 3 seconds. this is the code:
Server:
import socket
import zlib
def conv(code):
with open('Image2.pgm', 'wb') as f:
f.write(code)
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 100000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connection address:', addr
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
str = zlib.decompress(data)
conv(str)
print "All OK"
conn.send(data) # echo
conn.close()
Client:
import socket
import pyscreenshot as ImageGrab
import zlib
def PrtSc():
ImageGrab.grab_to_file("Image.pgm")
f = open("Image.pgm", "rb")
Image = f.read()
Image = zlib.compress(Image)
return Image
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 100000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(PrtSc())
data = s.recv(BUFFER_SIZE)
s.close()
print "received data:", data
Thanks :)

Python Tcp disconnect detection

I have a simpletcp example:
import socket
import time
TCP_IP = '127.0.0.1'
TCP_PORT = 81
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
while True:
s.send(bytes('hello', 'UTF-8'))
time.sleep(1)
s.close()
How can I detect, if I lost the connection to the server, and how can I safely reconnect then?
Is it necessary to wait for answer to the server?
UPDATE:
import socket
import time
TCP_IP = '127.0.0.1'
TCP_PORT = 81
BUFFER_SIZE = 1024
def reconnect():
toBreak = False
while True:
s.close()
try:
s.connect((TCP_IP, TCP_PORT))
toBreak = True
except:
print ("except")
if toBreak:
break
time.sleep(1)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
while True:
try:
s.send(bytes('hello', 'UTF-8'))
print ("sent hello")
except socket.error as e:
reconnect()
time.sleep(1)
s.close()
If I break the connection, it raises an error (does not really matter what), and goes to the
reconnect loop. But after I restore the connection, the connect gives back this error:
OSError: [WinError 10038] An operation was attempted on something that is not a socket
If I restart the script, which calls the same s.connect((TCP_IP, TCP_PORT)), it works fine.
You'll get a socket.error:[Errno 104] Connection reset by peer exception (aka ECONNRESET) on any call to send() or recv() if the connection has been lost or disconnected. So to detect that, just catch that exception:
while True:
try:
s.send(bytes('hello', 'UTF-8'))
except socket.error, e:
if e.errno == errno.ECONNRESET:
# Handle disconnection -- close & reopen socket etc.
else:
# Other error, re-raise
raise
time.sleep(1)
Use a new socket when you attempt to reconnect.
def connect():
while True:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
return s.makefile('w')
except socket.error as e:
log("socket error {} reconnecting".format(e))
time.sleep(5)
dest = connect()
while True:
line = p.stdout.readline()
try:
dest.write(line)
dest.flush()
except socket.error as e:
log("socket error {} reconnecting".format(e))
dest = connect()
Can you try that (I think that you does'not try socket.SO_REUSEADDR):
def open_connection():
data0=''
try:
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Connect the socket to the port where the server is listening
server_address = ('192.168.0.100', 8000)
sock.settimeout(10) # TimeOut 5 secunde
while True:
try:
sock.connect(server_address)
message = 'new connection'
sock.sendall(message)
# Look for the response
amount_received = 0
data0=sock.recv(1024)
amount_received = len(data0)
return
finally:
wNET = 0
pass
except:
sock.close()
time.sleep(60)
del data0
This is the code based on thread. The main tip is that the received buffer cannot be none, if the socket is connected.
import time
import socket
import threading
def connect():
while True:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.settimeout(60)
return s
except socket.error as e:
print("socket error {} reconnecting".format(e))
time.sleep(5)
soc = connect()
def runSocket():
global soc
while True:
try:
recBuf = soc.recv(64)
if recBuf == b'': #remote server disconnect
soc = connect()
else:
print(recBuf)
except socket.timeout:
print("Timeout")
except Exception as e:
print("other socket error {}".format(e))
soc = connect()
socketThread = threading.Thread(target=runSocket)
socketThread.start()

Categories