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')
Related
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()
I'm new to python programming. I want to create a simple TCP server working with an esp32. The idea of this is to send command data = '{\"accel\",\"gyro\",\"time\":1}' to esp32 via socket and then wait around 10ms for reply from esp32. I tried many examples but nothing works. ESP32 gets my message from this program but I can't receive message from esp32.
import socket
# bind all IP address
HOST = '192.168.137.93'
# Listen on Port
PORT = 56606
#Size of receive buffer
localhost=('0.0.0.0', 56606)
BUFFER_SIZE = 1024
# Create a TCP/IP socket
data = '{\"accel\",\"gyro\",\"time\":1}'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the host and port
s.connect((HOST, PORT))
# send data to server
s.send(bytearray(data, 'utf-8'))
s.serve_forever()
print('Listen for incoming connections')
sock.listen(1)
while True:
client, addr = s.accept()
while True:
content = client.recv(1024)
if len(content) ==0:
break
else:
print(content)
print("Closing connection")
client.close()
I tried more and tried to use other code(see below). Now I get message back but on other port(I can track it by wireshark)
import socket
# Ip of local host
HOST = '192.168.137.93'
# Connect to Port
PORT = 56606
#Size of send buffer
BUFFER_SIZE = 4096
# data to sent to server
message = '{\"accel\",\"gyro\",\"time\":1}'
# Create a TCP/IP socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to server
s.connect((HOST, PORT))
# send data to server
s.send(bytearray(message, 'utf-8'))
# Receive response from server
data = ""
while len(data) < len(message):
data = s.recv(BUFFER_SIZE)
# Close connection
print ('Server to Client: ' , data)
s.close()
I don't use both of these codes together.
Any hints?
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.
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”
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. 😉