Sendign a file over TCP connection - python

Im trying to send a file over TCP connection and im spected to receive an accio command but, im having trobule doing that, im getting this error:PS C:\Users\mpgm1\PycharmProjects\pythonProject1> py client.py 131.94.128.43 54634 file.txt
4 131.94.128.43 54634 file.txt
confirm-accio
confirm-accio-again
Sending...
Done Sending
b'ERROR: No data expected until the accio command is issued!'
Here is the code:
import selectors
from socket import *
import sock
import sys
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]
# 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))
print("confirm-accio\r\n")
print("confirm-accio-again\r\n")
fileToSend = open("file.txt", "rb")
print("Sending...")
while True:
data = fileToSend.read()
if not data:
break
s.send(data)
fileToSend.close()
s.send(b"Done")
print("Done Sending")
print(s.recv(1024))
s.close()

Related

Send commands via socket with python

I wanted to make a server that sends this command by socket
img = cv2.imread('cat.jpg',0)
cv2.imshow('cat.jpg',img)
cv2.waitKey(0)
for a client, I don't want to send a file, I want to send a command, but how do I do that, please?
Server
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', 7777))
print('ouvindo conexões\n')
server.listen(1)
connection, adress = server.accept()
namefile = connection.recv(1024).decode()
with open(namefile, 'rb') as file:
for data in file.readlines():
connection.send(data)
print('Arquivo enviado')
Client
import socket
client = server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost',7777))
print('Conectado!\n')
namefile = str(input('Arquivo'))
client.send(namefile.encode())
with open(namefile, 'wb') as file:
while 1:
data = client.recv(1000000)
if not data:
break
file.write(data)
print(f'{namefile}recebido\n')

How to Send a file with keeping its extension through a python socket?

I'm trying to send one file which is txt file through a python socket. I want the txt file which is received by the client keeps its extension which is txt.
Here is my server's side:
import socket
port = 50000
s = socket.socket()
host = "localhost"
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('Server received', repr(data))
filename='file.txt'
f = open(filename,'rb')
while (f):
conn.send(filename)
f.close()
print('Done sending')
conn.close()
Here is my client's side:
import socket # Import socket module
s = socket.socket() # Create a socket object
host = "localhost" #Ip address that the TCPServer is there
port = 50000 # Reserve a port for your service every new transfer wants a new port or you must wait.
s.connect((host, port))
s.send("Hello server!")
while True:
print('receiving the file...')
data = s.recv()
if not data:
break
print('Successfully get the file')
s.close()
print('connection closed')
All I found online is either modifying this file or sending a text in that file.

sending file through socket in python 3

In the code below I've tried to send an image using the python socket module in one machine to another machine. So I have 2 files: client.py and Server.py
as I figured it out the problem is when I read the image(as bytes) at the client machine and then the server tries to receive the file, at that moment when sending process is done before the receiving process then the error below occurs at line 13 of the client code:
BrokenPipeError: [Errno 32] Broken pipe
I want to find out what this error is and why does it occur in my code.
Server.py
import socket
host = '192.168.1.35'
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(1)
while True:
conn , addr = s.accept()
data = conn.recv(1024)
with open(r"C:\Users\master\Desktop\music.jpg",'wb') as f:
f.write(data)
# conn.send(b'done')
data = conn.recv(1024)
if not data:
break
conn.send(b'done')
conn.send(b'done')
conn.close()
s.close()
Client.py
import socket
def main():
HOST = '192.168.1.35'
PORT = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
f = open('/home/taha/Desktop/f.jpg','rb')
data = f.read()
s.sendfile(f)
if s.recv(1024) == b'done':
f.close()
s.close()
if __name__ == '__main__':
main()
You are closing the server connection before the client read the “done”

Windows 10 - VB 5.2.4 with Ubuntu 16.04: Sending files between two VMs with Python

I'm new to python and this time I want to send a file between two VMs, first of all, the VMs are configured with NAT Network, both VMs can ping each other. The codes are the following:
Server side:
#server.py
import socket # Import socket module
port = 60000 # Reserve a port for your service.
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
# s.bind((host, port)) # Bind to the port
s.bind(('', port))
s.listen(5) # Now wait for client connection.
print 'Server listening....'
while True:
conn, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
data = conn.recv(1024)
print('Server received', repr(data))
filename='runbonesi.py'
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.shutdown(socket.SHUT_WR)
print conn.recv(1024)
conn.close()
client side:
#client.py
import socket # Import socket module
s = socket.socket() # Create a socket object
#host = socket.gethostname() # Get local machine name
host = '10.0.2.15'
port = 60000 # Reserve a port for your service.
s.connect((host, port))
with open('received_file', 'wb') as f:
print 'file opened'
while True:
print('receiving data...')
data = s.recv(1024)
print('data=%s', (data))
if not data:
break
# write data to a file
f.write(data)
f.close()
print('Successfully get the file')
s.close()
print('connection closed')
The results can be seen in the following pictures:
Server side:
result on server
Client side:
result on client
The problem is, the client didn't receive the file as .py format, it only received as txt files. Please help me resolve this issue.
Thank you.
After s.connect((host, port)) in the client script you have to write s.send(...) with 'hello', for example. You also forgot to write the file extension '.py' in with open(...) (only if you want to save the file as Python script!). And you also have to add s.send(...) before you close the connection on the client side. 😉

Python : How to handle multiple clients and a server

I am implementing a program with a server and multiple clients. All clients send data to the server and a server check out the step of each client. If all client's steps are the same, a server sends new data to all clients to do next step. And it continues this procedure again and again.
However, when I run my program, it cannot communicate each other. Here are my code. Would you give me some hints?
client & server
#client
from socket import *
from sys import *
import time
import stat, os
import glob
# set the socket parameters
host = "localhost"
port = 21567
buf = 1024
data = ''
addr = (host, port)
UDPSock = socket(AF_INET, SOCK_DGRAM)
UDPSock.settimeout(100)
def_msg = "=== TEST ==="
#FILE = open("test.jpg", "w+")
FILE = open("data.txt","w+")
while (1):
#data, addr = UDPSock.recvfrom(buf)
print "Sending"
UDPSock.sendto(def_msg, addr)
#time.sleep(3)
data, addr = UDPSock.recvfrom(buf)
if data == 'done':
FILE.close()
break
FILE.write(data)
print "Receiving"
#time.sleep(3)
UDPSock.close()
# server program for nvt
from socket import *
import os, sys, time, glob
#import pygame
import stat
host = 'localhost'
port = 21567
buf = 1024
addr = (host, port)
print 'test server'
UDPSock = socket(AF_INET, SOCK_DGRAM)
UDPSock.bind(addr)
msg = "send txt file to all clients"
#FILE = open("cam.jpg", "r+")
FILE = open("dna.dat","r+")
sending_data = FILE.read()
FILE.close()
tmp_data = sending_data
while (1):
#UDPSock.listen(1)
#UDPSock.sendto(msg, addr)
#FILE = open("gen1000.dat","r+")
#sending_data = FILE.read()
#FILE.close()
#print 'client is at', addr
data, addr = UDPSock.recvfrom(buf)
#time.sleep(3)
print data
#msg = 'hello'
#
tmp, sending_data = sending_data[:buf-6], sending_data[buf-6:]
if len(tmp) < 1:
msg = 'done'
UDPSock.sendto(msg, addr)
print "finished"
sending_data = tmp_data
UDPSock.sendto(tmp, addr)
print "sending"
#time.sleep(3)
UDPSock.close()
A server must perform the sequence socket(), bind(), listen(), accept() (possibly repeating the accept() to service more than one client), while a client only needs the sequence socket(), connect().
Your missing listen() i saw first. Listen for connections made to the socket.
More on this here: link text
Look at this: http://heather.cs.ucdavis.edu/~matloff/Python/PyNet.pdf
It's a very good Python networking tutorial including working examples of a client and server. Now, I'm not an expert on this, but it looks to me like your code is overcomplicated. And what's the deal with all the commented-out lines?
Quote from question:
#UDPSock.listen(1)
#UDPSock.sendto(msg, addr)
#FILE = open("gen1000.dat","r+")
#sending_data = FILE.read()
#FILE.close()
End quote
Those look like some pretty important lines to me.
Also, make sure the computers are connected. From a prompt run:
ping [IP]
where [IP] is the IP address of the other machine(Note: if you're not connected to the same LAN, this becomes much harder as you might then need port forwarding and possibly static IPs).

Categories

Resources