the socket disconnect when running client\server python - python

I am having a client-server program to send from the server to the client
the server in a different folder from the client (like there is a folder for the server code and another folder for the client code)
-when running the server and the client the server gives me an error that the socket disconnect and i don't know why:
Traceback (most recent call last):
File "server.py", line 30, in
s.send(ans.encode(FORMAT))
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 s
upplied
the server code:
import socket
import os
import json
SIZE = 1024
FORMAT = "utf-8"
# creating a TCP socket
print('\n','_'*50,"\n\nThe server started.. ")
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(("127.0.0.1", 5100))
# converted into passive socket - queue up to 2 requests
print("\n\nThe server is listening.. ")
s.listen(5)
while True:
cli, sockname = s.accept()
print('Accepted request from', sockname[0], 'with port number', sockname[1])
listoffile= [x for x in os.listdir() if x.endswith(".txt")]
ans =json.dumps(listoffile)
thelist=ans.replace(',','\n').replace('[',"").replace('"',"").replace(']',"")+"\n exit"
print('\n The server will send the list to the client:\n',thelist)
s.sendall(ans.encode(FORMAT))
rec = cli.recv(SIZE).encode(FORMAT)
if rec != 'exit':
with open(rec,'rb') as f:
filetosend =f.read(SIZE)
s.sendall(filetosend.encode(FORMAT))
elif rec == 'exit':
cli.close()
s.close()
The client code:
import socket
host = '127.0.0.1'
port = 5100
SIZE = 1024
FORMAT = "utf-8"
# creating a TCP socket
print('\n','_'*50,"\n\nThe client side started.. ")
c = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
c.connect((host, port))
while True:
msg = c.recv(SIZE).decode(FORMAT)
msg=msg.replace(',','\n').replace('[',"").replace('"',"").replace(']',"")+"\n exit"
print(f"Choose one of the file to get a copy: {msg}")
filename = input("Enter the file name or exit to quit:")
if filename != 'exit':
c.send(filename.encode(FORMAT))
f=open(filename,'wb')
data=c.recv(SIZE)
f.write(data)
print('The file {filename} is copied.')
elif filename == 'exit':
c.close()

Related

server.send(join.encode('utf-8')) gives me this error

I get this error when i connect on the client.
felix+
Traceback (most recent call last):
File "c:\Users\felix\Documents\CODE\Uno02\uno02_server.py", line 23, in <module>
server.send(join.encode('utf-8'))
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
The client simply receives some information from the user, and connects to the server. I am not sure what I typed wrong
Client code:
import socket
server_ip = input("Enter the server IP: ")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((server_ip,42069))
name = input("Please enter a username: ")
client.send(name.encode())
while True:
server_msg = client.recv(1024)
print(server_msg.decode())
and server code:
name_list = []
ip_list = []
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("127.0.0.1",42069))
server.listen()
while(True):
(clientConnected, clientAddress) = server.accept()
print("connection gained %s:%s"%(clientAddress[0], clientAddress[1]))
clientdata = clientConnected.recv(1024)
name = clientdata.decode()
join = name + " joined"
name_list.append(clientdata)
ip_list.append(clientAddress[0])
print(name+"+")
server.send(join.encode('utf-8'))
Replace
server.send(join.encode('utf-8'))
by
clientConnected.send(join.encode('utf-8'))
check Python TCP Communication for further details

Sending a file over TCP connection

I want to send i file over TCP but when i try to run this the connection fails, the server receives the file but it gives this error: ERROR: Client timed out before sending a file
import selectors
import sys
from socket import *
import sock
sel1 = selectors.DefaultSelector()
print(len(sys.argv), sys.argv[1], sys.argv[2], sys.argv[3])
host = sys.argv[1]
port = int(sys.argv[2])
file = sys.argv[3]
try:
# Instaniating socket object
s = socket(AF_INET, SOCK_STREAM)
# Getting ip_address through host name
host_address = gethostbyname(host)
# Connecting through host's ip address and port number using socket object
s.connect((host_address, port))
sel1.register(
sock,
selectors.EVENT_READ, data = None)
fileToSend = open("file.txt", "rb")
data = fileToSend.read(1024)
while data:
print("Sending...")
fileToSend.close()
s.send(b"Done")
print("Done Sending")
print(s.recv(1024))
s.shutdown(2)
s.close()
except:
# Returning False in case of an exception
sys.stderr.write("Connection Failed")
Do the writing in a loop. There's no particular reason to chop it into 1024-byte pieces; the network stack will handle that for you.
By the way, your "Done" signal is not a good idea, especially since you're writing a binary file that might very well contain the word "Done". Remember that TCP is a streaming protocol. The other end does not see the exact packets you're sending. That is, just because you send 1024 bytes and 4 bytes, the other end might see it as reads of 256 and 772 bytes.
# Instaniating socket object
s = socket(AF_INET, SOCK_STREAM)
# Getting ip_address through host name
host_address = gethostbyname(host)
# Connecting through host's ip address and port number using socket object
s.connect((host_address, port))
fileToSend = open("file.txt", "rb")
print("Sending...")
while True:
data = fileToSend.read(1024)
if not data:
break
s.send( data )
fileToSend.close()
s.send(b"Done")
print("Done Sending")
print(s.recv(1024))
s.close()

How to encode traffic socket?

Hi i have my server client model i need to encode the traffic which is HTTP1.1 how should i do this this is my server code
server:
import socket
from base64 import b64encode
SERVER_HOST = "0.0.0.0"
SERVER_PORT = 5003
BUFFER_SIZE = 1024
# create a socket object
s = socket.socket()
# bind the socket to all IP addresses of this host
s.bind((SERVER_HOST, SERVER_PORT))
# make the PORT reusable
# when you run the server multiple times in Linux, Address already in use error will raise
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.listen(5)
print(f"Listening as {SERVER_HOST}:{SERVER_PORT} ...")
# accept any connections attempted
client_socket, client_address = s.accept()
print(f"{client_address[0]}:{client_address[1]} Connected!")
# just sending a message, for demonstration purposes
message = "Hello and Welcome".encode()
client_socket.send(message)
while True:
# get the command from prompt
command = input("Enter the command you wanna execute:")
# send the command to the client
if command == "3":
command2 = "arp -a"
client_socket.send(command2.encode())
else:
client_socket.send(command.encode())
if command.lower() == "exit":
# if the command is exit, just break out of the loop
break
# retrieve command results
results = client_socket.recv(BUFFER_SIZE).decode()
# print them
print(results)
# close connection to the client
client_socket.close()
# close server connection
s.close()
and this is what i am trying to do:
How should i achive this thanku.
First you should have encryption and decryption mechanism both on
server side and client side depending on your needs.
The next thing is to use Web Socket Secure Protocol (WSS) Configured
in your web server.

'b' is getting passed when sending string from client to server in python while trying FTP implementation

I am trying to implement to implement FTP where I want to send Filename to server from client, I have tried below code, when I give file name as myText.txt but server is receiving as 'b"myText.txt'"
Can you please help me how can I get rid of b ?
This is the output on server:
This is server code:
import socket # Import socket module
port = 60000 # Reserve a port for your service.
socketObj = socket.socket() #Create a socket object
host = socket.gethostname() # Get local machine name
socketObj.bind((host, port)) # Bind to the port
socketObj.listen(5) # Now wait for client connectionection.
print ('Server listening....')
while True:
connection, addr = socketObj.accept() # Establish connectionection with client.
print ('Got connectionection from', addr)
data = connection.recv(1024)
print('Server received request for FTS of',(data))
filename=(repr(data))
f = open(filename,'rb')
l = f.read(1024)
while (l):
connection.send(l)
print('Sent ',repr(l))
l = f.read(1024)
f.close()
print('Done sending')
connection.send(('Thank you for connectionecting').encode())
connection.close()
This is the client code
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 60000 # Reserve a port for your service.
s.connect((host, port))
fileNeeded = input("What File do you need, please enter the name:")
s.send(fileNeeded.encode())
fileToBeSaved = input("Enter file name to save requested file")
with open(fileToBeSaved, 'wb') as f:
print ('file opened')
while True:
print('receiving data...')
data = s.recv(1024)
print((data))
if not data:
break
# write data to a file
f.write(data)
f.close()
print('Successfully got the file')
s.close()
print('connection closed')
The following is received in server:
Server received request for FTS of b'mytext.txt'
You can use the bytes.decode() method to convert bytes into a string:
Change:
filename=(repr(data))
to:
filename=repr(data).decode()

Python Client-server problems

I am making a chat program.
I have a (TCP) server which creates a new thread for every connection request it gets.
I'm having problems when the client quits/terminates connection. The server raises an error(below). How do I handle it?
And, the server has to send the 'data' it receives from one client to another (changeable) client.
How do I implement this??
I receive this error when the client quits :
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python2.7 For Chintoo\lib\threading.py", line 552, in __bootstrap_inner
self.run()
File "C:\Python2.7 For Chintoo\lib\threading.py", line 505, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\Users\karuna\Desktop\Jython\Python\My Modules\Network\Multi-server.py", line 23, in recv_loop
data = client.recv(1024)
error: [Errno 10054] An existing connection was forcibly closed by the remote host
My scripts:
Multi-server.py
import os, socket, time, threading, random
class Server:
def __init__(self,host,port,user):
self.port = port
self.host = host
self.user = user
self.bufsize = 1024
self.addr = (host,port)
self.socket = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
self.socket.bind(self.addr)
print "Server running on",host,"at port",port
self.socket.listen(5)
def recv_loop(server,client,caddr):
print 'Connected To',caddr
while True:
global clients
name = clients[client]
data = client.recv(1024)
if not data:
break
print name + " said: " + data
client.close()
host = 'localhost'
port = random.randint(1025,60000)
user = 'No one'
server = Server(host, port, user)
clients = {}
threads = []
while True:
client, caddr = server.socket.accept()
# name extraction
name = client.recv(1024)
clients[client] = name
thread = threading.Thread(target=recv_loop, args=(server,client, caddr))
thread.start()
client.py
from socket import *
host = 'localhost'
name = raw_input('Enter name: ')
port = int(raw_input('Enter server port: '))
bufsiz = 1024
addr = (host, port)
tcpClient = socket(AF_INET , SOCK_STREAM)
tcpClient.connect(addr)
# sending name
tcpClient.send(name)
while True:
data = raw_input('> ')
if not data:
break
tcpClient.send(data)
raw_input('Enter to Quit')
Problem 1
Just close the socket connection at client side:
raw_input('Enter to Quit')
tcpClient.close()
Problem 2
You are looking at producer consumer problem here.
Basic solution:
Receiving loop should acquire a threading.Condition, update a global array and call notifyAll. Sending loops should acquire the condition, read data from the array and send to client.
I haven't done socket programming in Python, but you might want to cleanly close your socket connection before the client quits. I would use close method in the client.

Categories