I have a video file and want to send it over socket. Video is send to the client but video is not playable and also video size received is 2 KB. And acutely video size is 43 MB. What is the problem?
Server:
import socket
try:
soc = socket.socket()
print('socked created.')
host = ''
port = 8080
soc.bind((host, port))
print('soc bound.')
soc.listen(10)
print('waiting for connecting...')
con, addr = soc.accept()
print('server connected to IP: ' + addr[0] + " port: " + str(addr[1]))
while True:
filename = input('enter filename: ')
file = open(filename, 'rb')
sendfile = file.read(9000000)
con.send(sendfile)
print("file has been send.")
break
con.close()
soc.close()
except socket.error as err:
print('error ', str(err))
client:
import socket
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('socked created. waiting for connecting to server...')
server_address = ("192.168.1.3", 8080)
soc.connect(server_address)
print('connected to the server.')
while True:
recvfile = soc.recv(9000000)
savefilebyname = input("enter file name: ")
openfile = open(savefilebyname, 'wb')
openfile.write(recvfile)
openfile.close()
break
print("File has been received.")
soc.close()
Check the return value of send and recv. The 9000000 value is a maximum but not guaranteed value to send/recv. Alternatively, use sendall.
For recv, you have to loop until you receive all the data. If you close the socket after the file is sent, recv will return zero when all the data is received.
FYI, your while True: in both files never loops due to the break, so they are unnecessary.
Here's something that should work...
server.py
import socket
soc = socket.socket()
soc.bind(('',8080))
soc.listen(1)
print('waiting for connection...')
with soc:
con,addr = soc.accept()
print('server connected to',addr)
with con:
filename = input('enter filename to send: ')
with open(filename, 'rb') as file:
sendfile = file.read()
con.sendall(sendfile)
print('file sent')
client.py
import socket
soc = socket.socket()
soc.connect(('localhost',8080))
savefilename = input("enter file name to receive: ")
with soc,open(savefilename,'wb') as file:
while True:
recvfile = soc.recv(4096)
if not recvfile: break
file.write(recvfile)
print("File has been received.")
Related
I'm creating a udp file transfer using python with a client (requests file from server), a server (receives request from client and passes it to the relevant worker) and worker1/worker2 (recieve request from server, if file exists, sends to server to pass back to client) and its all ran in docker containers with an ubuntu image*
Currently, when I type the name of the file I want in the client container, nothing works. I think the file name isn't actually being sent to the server but I can't figure out why at all. I was wondering if anyone can spot my mistake?
Server:
from fileinput import filename
import socket
import time
localIP = "127.0.0.1"
localPort = 50001
bufSize = 1024
msg = "Server is connecting..."
print(msg)
workerAddressPorts = [('127.0.0.1', 50002), ('127.0.0.1', 50003)]
# Create datagram sockets and bind to address and ip
UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
UDPServerSocket.bind((localIP, localPort))
print("Server is waiting for packet...")
while True:
bytesAddressPair = UDPServerSocket.recvfrom(bufSize)
clientBuf = bytesAddressPair[0]
clientAddr = bytesAddressPair[1]
msgFrom = 'Message from Client:{}'.format(clientBuf.decode('utf-8'))
print(msgFrom)
for workerAddressPort in workerAddressPorts:
UDPServerSocket.sendto(clientBuf, workerAddressPort) # send file name to worker
print(f'Clients request has been sent to Worker {workerAddressPort[0]}')
workerBuf = UDPServerSocket.recvfrom(bufSize)[0] # saving data from worker
print(f'Request recieved.')
UDPServerSocket.sendto(workerBuf, clientAddr) # sending data to client
print('Packet from Worker has been sent to Client')
while not workerBuf: # split file to prevent buffer overflow
workerBuf = UDPServerSocket.recvfrom(bufSize)[0]
print(f'Packet received.')
UDPServerSocket.sendto(workerBuf, clientAddr)
print('Packet from worker has been sent to Client')
print('File has been sent to Client.')
Client:
import sys
msgFrom = input('Name of file: ')
print(msgFrom)
bytesToSend = str.encode(msgFrom, 'utf-8')
serverAddressPort = ("127.0.0.1", 50001)
bufSize = 1024
# create UDP Client Socket and send to server
UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
UDPClientSocket.sendto(bytesToSend, serverAddressPort)
while (True):
try:
serverBuf = UDPClientSocket.recvfrom(bufSize)[0]
if len(serverBuf) > 0:
print('Packet incoming...')
msg = serverBuf.decode('utf-8')
if msg == 'NO_FILE':
print('No such file exists.')
break
elif msg == 'END_OF_FILE':
print('Empty file.')
break
else:
f = open(msgFrom, 'wb')
f.write(serverBuf)
f.close()
except Exception as e:
print(e)
Worker:
import socket
import time
from os.path import exists
bufSize = 1024
msg = "Worker is connecting..."
print(msg)
serverAddressPort = ("127.0.0.1", 50001)
# Create a datagram socket and bind to address and ip
UDPWorkerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
UDPWorkerSocket.bind(('127.0.0.1', 50002))
print("Worker is connected and waiting...")
while True:
time.sleep(1)
bytesAddressPair = UDPWorkerSocket.recvfrom(bufSize)
msg = bytesAddressPair[0]
addr = bytesAddressPair[1]
print('Packet Incoming...')
file_name = msg.decode('utf-8')
script_dir = os.path.dirname("C:/Users/Vic/Documents/3rd Year TCD/CSU33031 Computer Networks/Assignments/Assignment1.3/Files to send")
abs_file_path = os.path.join(script_dir, file_name)
if exists(file_name):
f = open(file_name, 'rb')
data = f.read(bufSize)
while data:
if UDPWorkerSocket.sendto(data, serverAddressPort):
data = f.read(bufSize)
time.sleep(1)
print('Sent to Server.')
else:
UDPWorkerSocket.sendto(str.encode('NO_FILE'), serverAddressPort)
print(f'{file_name} was not found. Moving to next available worker..')
Hoping that the for statement in the server, iterates the two worker files(only included one) so if it can't find the file in one worker it moves to the other
*the client is connected to a different network as the two workers. The server is connected to both networks
Thanks in advance!!
So I have successfully created a socket connection to one client and another, but I am having trouble getting them to switch from one another with loops, did some while true and if statements to make the program recognize when one system wants to switch based on user input but I don't think I'm doing it right. Can some one help me out with a code to switch back and forth
The following is the code I'm attempting to implement.
This is the code on my computer:
import socket,sys,os,time
T2='yourturn'
serverAddr = ('192.168.0.120', 20104)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#client.connect(serverAddr)
sock = client
client.connect(('192.168.0.120', 20104))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def redirectOut(port=20104, host='192.168.0.11'):
"""
connect caller's standard output stream to a socket for GUI to listen
start caller after listener started, else connect fails before accept
"""
sock = client
# caller operates in client mode
file = sock.makefile('w') # file interface: text, buffered
sys.stdout = file
# make prints go to sock.send
return sock
########################################33333
time.sleep(10)
HOST = ''
PORT2 = 20105
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
try:
l=s.bind((HOST, PORT2))
except socket.error as msg:
print('Bind failed. ')
sys.exit()
print('Socket bind complete')
s.listen(10)
print('Socket now listening')
conn, addr = s.accept()
print('Connected to ' + addr[0] + ':' + str(addr[1]))
####################################################
time.sleep(10)
while True:
if T2!='yourturn':
data = conn.recv(1024)
line = data.decode # convert to string (Python 3 only)
T2=print(line)
else :
if T2=='myturn':
break
else:
redirectOut()
T2=print(input())
this is the code on my begalbone black:
import socket
import sys
import os, time
HOST = ''
PORT2 = 20104
T='yourturn'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
try:
l=s.bind((HOST, PORT2))
except socket.error as msg:
print('Bind failed. ')
sys.exit()
print('Socket bind complete')
s.listen(10)
print('Socket now listening')
conn, addr = s.accept()
print('Connected to ' + addr[0] + ':' + str(addr[1]))
#################################################################
time.sleep(15)
serverAddr = ('192.168.0.11', 20105)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock = client
try:
sock.connect(('192.168.0.11', 20105))
fsr = 'P9_40'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except TimeoutError:
os.system('reboot')
def redirectOut(port=20105, host='192.168.0.120'):
"""
connect caller's standard output stream to a socket for GUI to listen
start caller after listener started, else connect fails before accept
"""
sock = client
# caller operates in client mode
file = sock.makefile('w') # file interface: text, buffered
sys.stdout = file # make prints go to sock.send
return sock
##############################################################
time.sleep(10)
while True:
if T!='myturn':
data = conn.recv(1024)
line = data.decode('UTF-8') # convert to string (Python 3 only)
T=print(line)
else:
redirectOut()
if T=='yourturn':
break
else:
T=print(input())
So tried this while loop: but its still hanging up, I think I'm close:
T2='yourturn'
while True:
#for line in 'Python':
print(T2)
time.sleep(10)
if T2=='myturn':
data = conn.recv(1024)
line = data.decode
print("myturn print")
l=print(line)
if l=="yourturn":
continue
if T2=="yourturn" or T2!='myturn':
print(T2)
print('myturn send')
redirectOut()# convert to string (Python 3 only)
k=input()
if k=="myturn":
T2='myturn'
continue
Tried the folowing but reciving machine is hanging up when myturn is input:
sending:
time.sleep(3)
T2='yourturn'
print('here')
while True:
#for line in 'Python':
#print(T2)
#time.sleep(10)
if T2=='myturn':
data = conn.recv(1024)
line = data.decode('UTF-8')
#print("myturn print")
l=print(line)
if l=="yourturn":
T2='yourturn'
continue
if T2=="yourturn" and T2!='myturn':
#print(T2)
#print('myturn send')
redirectOut()# convert to string (Python 3 only)
k=input()
print(k)
if k=="myturn":
T2=print('myturn')
T2='myturn'
print('there')
continue
receiving:
time.sleep(3)
T='yourturn'
while True:
#for line in 'Python':
#print(T)
if T=='yourturn':
data = conn.recv(1024)
line = data.decode('UTF-8')
#print("myturn print")
l=print(line)
if l=='myturn':
T='myturn'
continue
if l=='exit':
client.close()
break
if T=='myturn' and T!='yourturn':
#print('myturn send')
redirectOut()# convert to string (Python 3 only)
k=input()
print(k)
if k=='yourturn':
T=print('yourturn')
continue
EDIT SOLUTION:
I finally figured it out, removed my reditectOut function and opened the port with windows firewall to implement this code
my computer:
T2='yourturn'
while True:
if T2=='myturn':
data = conn.recv(1024)
line = data.decode('UTF-8')
print(line)
l=line
if l=="yourturn":
T2='yourturn'
continue
if T2=="yourturn" and T2!='myturn':
k=input()
client.sendto(k.encode('utf-8'),('192.168.0.120', 20104))
if k=="myturn":
T2='myturn'
continue
Beagle bone black:
time.sleep(3)
T='yourturn'
while True:
if T=='yourturn':
data = conn.recv(1024)
line = data.decode('UTF-8')
print(line)
l=line
if l=='myturn':
T='myturn'
continue
if T=='myturn' and T!='yourturn':
k=input()
client.sendto(k.encode('utf-8'),('192.168.0.11', 20105))
if k=='yourturn':
T='yourturn'
continue
I'm trying to send a large file (.avi) over socket by sending the content of the file in chunks (a little bit like torrents). The problem is that the script doesn't send the file. I'm out of ideas here.
Any help or twerking of the script would be very appreciated.
Server:
import socket
HOST = ""
PORT = 8050
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((HOST, PORT))
sock.listen(1)
conn, addr = sock.accept()
print("Connected by ", str(addr))
while 1:
data = conn.recv(1024)
if data.decode("utf-8") == 'GET':
with open(downFile,'rb') as output:
l = output.read(1024)
while (l):
conn.send(l)
l = output.read(1024)
output.close()
conn.close()
Client:
import socket
HOST = "localhost"
PORT = 8050
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST,PORT))
while 1:
message = input()
sock.send(bytes(message,'UTF-8'))
conn.send(str.encode('GET'))
with open(downFile, 'wb+') as output:
while True:
rec = str(sock.recv(1024), "utf-8")
if not rec:
break
output.write(rec)
output.close()
print('Success!')
sock.close()
Here are a working client and server that should demonstrate transferring a file over a socket. I made some assumptions about what your code was supposed to do, for example, I assumed that the initial message the client sent to the server was supposed to be the name of the file to download.
The code also includes some additional functionality for the server to return an error message to the client. Before running the code, make sure the directory specified by DOWNLOAD_DIR exists.
Client:
import socket
import sys
import os
HOST = "localhost"
PORT = 8050
BUF_SIZE = 4096
DOWNLOAD_DIR = "downloads"
def download_file(s, down_file):
s.send(str.encode("GET\n" + down_file))
rec = s.recv(BUF_SIZE)
if not rec:
return "server closed connection"
if rec[:2].decode("utf-8") != 'OK':
return "server error: " + rec.decode("utf-8")
rec = rec[:2]
if DOWNLOAD_DIR:
down_file = os.path.join(DOWNLOAD_DIR, down_file)
with open(down_file, 'wb') as output:
if rec:
output.write(rec)
while True:
rec = s.recv(BUF_SIZE)
if not rec:
break
output.write(rec)
print('Success!')
return None
if DOWNLOAD_DIR and not os.path.isdir(DOWNLOAD_DIR):
print('no such directory "%s"' % (DOWNLOAD_DIR,), file=sys.stderr)
sys.exit(1)
while 1:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((HOST, PORT))
except Exception as e:
print("cannot connect to server:", e, file=sys.stderr)
break
file_name = input("\nFile to get: ")
if not file_name:
sock.close()
break
err = download_file(sock, file_name)
if err:
print(err, file=sys.stderr)
sock.close()
Server:
import socket
import sys
import os
HOST = ""
PORT = 8050
BUF_SIZE = 4096
def recv_dl_file(conn):
data = conn.recv(1024)
if not data:
print("Client finished")
return None, None
# Get command and filename
try:
cmd, down_file = data.decode("utf-8").split("\n")
except:
return None, "cannot parse client request"
if cmd != 'GET':
return None, "unknown command: " + cmd
print(cmd, down_file)
if not os.path.isfile(down_file):
return None, 'no such file "%s"'%(down_file,)
return down_file, None
def send_file(conn):
down_file, err = recv_dl_file(conn)
if err:
print(err, file=sys.stderr)
conn.send(bytes(err, 'utf-8'))
return True
if not down_file:
return False # client all done
# Tell client it is OK to receive file
sent = conn.send(bytes('OK', 'utf-8'))
total_sent = 0
with open(down_file,'rb') as output:
while True:
data = output.read(BUF_SIZE)
if not data:
break
conn.sendall(data)
total_sent += len(data)
print("finished sending", total_sent, "bytes")
return True
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((HOST, PORT))
sock.listen(1)
keep_going = 1
while keep_going:
conn, addr = sock.accept()
print("Connected by", str(addr))
keep_going = send_file(conn)
conn.close() # close clien connection
print()
sock.close() # close listener
I've created a fairly simple server with the aim of sending a simple .txt file but it won't send for some reason.
Server code:
import socket
port = 8081
host = "192.168.0.20"
s = socket.socket()
s.bind((host, port))
s.listen(5)
print("Server Listening.....")
while True:
conn, addr = s.accept()
print("Got connection from", addr)
data = conn.recv(1024)
print("Data recieved", repr(data))
filename = "/Users/dylanrichards/Desktop/keysyms.txt"
f = open(filename, 'rb')
l = f.read(1024)
while (l):
conn.send(l)
print("Sent", repr(l))
l = f.read(1024)
f.close()
print("Done sending")
conn.send("Thank you for connecting")
conn.close()
Here is the code for the client:
import socket
port = 8081
host = "192.168.0.20"
s = socket.socket()
s.connect((host, port))
with open("Recieved_File", 'wb') as f:
print("File opened")
while True:
print("Receiving data...")
data = s.recv(1024)
print("Data=%s", (data))
if not data:
break
f = open("/Users/dylanrichards/Desktop/test12.txt")
f.write(data)
f.close()
print("Successfully got file")
print("Connection closed")
s.close()
Im testing this over my Local Network on a Macbook Air if thats any help. Thanks in advance...
Multiple file handles opened and all has same variable f
with open("Recieved_File", 'wb') as f: -- I think this is not required.
f = open("/Users/dylanrichards/Desktop/test12.txt")should be outside while loop.
While opening above file, add mode as 'wb'
Client Code :
import socket
port = 8081
host = "192.168.0.20"
s = socket.socket()
s.connect((host, port))
f = open("/Users/dylanrichards/Desktop/test12.txt",'wb')
while True:
print("Receiving data...")
data = s.recv(1024)
if not data:
break
print("Data=%s", (data))
f.write(data)
f.close()
print("Successfully got file")
print("Connection closed")
s.close()
Here is my server.py:
import socket, atexit
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((socket.gethostname(), 8000))
server.listen(5)
(client,(ip,port))=server.accept()
command = raw_input('> ')
if command.rsplit(' ',1)[0] == 'write':
client.send(command.rsplit(' ',1)[2])
print 'Client # ', ip + ' '
data = client.recv(1024)
file = open(command.rsplit(' ',1)[1],'rb')
bytes = file.read(1024)
while(bytes):
client.send(bytes)
bytes = file.read(1024)
file.close()
client.close()
The client.py:
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('MY IP', 8000))
client.send("!")
name = client.recv(1024)
with open(name, 'wb') as file:
while True:
data = client.recv(1024)
if not data:
break
file.write(data)
file.close()
client.close()
The first data transmission in server.py is supposed to send the name of the file I want to the client.py. Where it says:
name = client.recv(1024)
in client.py, it is supposed to receive and make a file using that name. However, the server.py closes, causing the client.py to crash and not give output (host closed). If I open in IDLE to see the output, it doesn't work but nothing shows.
Your server.py needed tweaked;
import socket, atexit
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('', 8000))
server.listen(5)
(client,(ip,port))=server.accept()
command = raw_input('> ')
if command.split(' ')[0] == 'write':
client.send(command.split(' ')[2])
print 'Client # '+str(ip)+':'
data = client.recv(1024)
file = open(command.split(' ')[1],'rb')
bytes = file.read(1024)
while(bytes):
client.send(bytes)
bytes = file.read(1024)
file.close()
client.close()
The rsplit and trailing ,1's were causing the breaks.
Using the input write /Users/Namelessthehckr/Downloads/ucsgflmza.cs /Users/Namelessthehckr/Desktop/Test.txt, the file was successfully CP'd without error.