I want to send images and text for the server from the client file. But since I'm new to the socket, I don't know how to do it. Please help me.
codes:
#server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("localhost", 1236))
s.listen(5)
c, addr = s.accept()
image_datas, d1, d2 = c.recv(1024)
f = open("C:\\Users\\SD\\Desktop\\image.jpg", "wb")
while image_datas:
f.write(image_datas)
image_datas = c.recv(1024)
print(d1,d2)
f.close()
c.close()
s.close()
#client.py
import socket
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.connect(("tcp.ngrok.io", ))
f = open("image.jpg", "rb")
img_data = f.read()
data1 = "hello"
data2 = "server"
c.send(img_data,data2,data3)
f.close()
c.close()
Related
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().
I am trying this scenario:
Client sends file to server
Server updates on file and save it
Sends updated file back to client
Steps 1 and 2 are done correctly as I wanted but when client finishes sending the socket closes. I've tried this code but its not working. Any suggestions?
Client:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
H = socket.gethostname()
P = 1111
s.connect((H,P))
with open('File.txt', 'rb') as fileName:
for data in fileName:
s.sendall(data)
with open('ReFile.txt', 'wb') as File:
while True:
data = s.recv(1024)
print data
if not data:
break
File.write(data)
File.close()
Server:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
H= socket.gethostname()
P = 1111
s.bind((H, P))
s.listen(6)
c, address = s.accept()
print 'Connection with ' , address
with open('ReFile.txt', 'wb') as RecFile:
while True:
data = c.recv(1024)
print data
if not data:
break
RecFile.write(data)
RecFile.write("updated version")
RecFile.close()
with open('ReFile.txt', 'rb') as file:
for data in file:
s.sendall(data)
s.close()
Try this:
Server:
import socket
s = socket.socket()
H = socket.gethostname()
P = 1111
s.bind((H, P))
s.listen(6)
c, address = s.accept()
print 'Connection with ', address
lenF = int(c.recv(1024))
if lenF != 0:
c.sendall('Send data')
data = c.recv(lenF)
data += "\nUpdated Version"
RecFile = open('ReFile.txt','w')
RecFile.write(str(data))
RecFile.close()
fileN = open('ReFile.txt')
data = fileN.read(-1)
fileN.close()
lenF = len(data)
c.send(str(lenF))
if c.recv(5) == 'Ready':
c.send(data)
Here I am using lenF variable to get the size of file that I am getting from the client.
Client:
import socket
s = socket.socket()
H = socket.gethostname()
P = 1111
s.connect((H,P))
fileName = open('file.txt')
data = fileName.read(-1)
fileName.close()
dataL = int(len(data))
s.send(str(dataL))
validCheck = s.recv(9)
if validCheck == 'Send data':
print 'Sending file.......'
s.send(data)
dataL = int(s.recv(1024))
if dataL != 0:
s.send('Ready')
data = s.recv(dataL)
File = open('ReFile.txt','w')
File.write(data)
File.close()
Here I am using dataL variable to receive data length(file) and sending it.
I am writing a simple python tcp code to send over a wav file however I seem to be getting stuck. can someone explain why my code is not working correctly?
Server Code
import socket, time
import scipy.io.wavfile
import numpy as np
def Main():
host = ''
port = 3333
MAX = 65535
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(1)
print "Listening on port..." + str(port)
c, addr = s.accept()
print "Connection from: " + str(addr)
wavFile = np.array([],dtype='int16')
i = 0
while True:
data = c.recvfrom(MAX)
if not data:
break
# print ++i
# wavfile = np.append(wavfile,data)
print data
timestr = time.strftime("%y%m%d-%h%m%s")
print timestr
# wavF = open(timestr + ".wav", "rw+")
scipy.io.wavfile.write(timestr + ".wav",44100, data)
c.close()
if __name__ == '__main__':
Main()
Client Code
host, port = "", 3333
import sys , socket
import scipy.io.wavfile
# create a tcp/ip socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect the socket to the port where the server is listening
server_address = (host, port)
print >>sys.stderr, 'connecting to %s port %s' % server_address
input_data = scipy.io.wavfile.read('Voice 005.wav',)
audio = input_data[1]
sock.connect(server_address)
print 'have connected'
try:
# send data
sock.sendall(audio)
print "sent" + str(audio)
sock.close()
except:
print('something failed sending data')
finally:
print >>sys.stderr, 'closing socket'
print "done sending"
sock.close()
Please help someone, I want to send an audio file to my embedded device with tcp since it crucial data to be processed on the embedded device.
Not sure why you go to the trouble of using scipy and numpy for this, since you can just use the array module to create binary arrays that will hold the wave file. Can you adapt and use the simple client/server example below?
(Note: I've copy/pasted a small Windows sound file called 'tada.wav' to the same folder to use with the test scripts.)
Code for the server script:
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
print('Listening...')
conn, addr = s.accept()
print('Connected by', addr)
outfile = open("newfile.wav", 'ab')
while True:
data = conn.recv(1024)
if not data: break
outfile.write(data)
conn.close()
outfile.close()
print ("Completed.")
Code for the client:
from array import array
from os import stat
import socket
arr = array('B') # create binary array to hold the wave file
result = stat("tada.wav") # sample file is in the same folder
f = open("tada.wav", 'rb')
arr.fromfile(f, result.st_size) # using file size as the array length
print("Length of data: " + str(len(arr)))
HOST = 'localhost'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(arr)
print('Finished sending...')
s.close()
print('done.')
This works for me (though only tested by running both on localhost) and I end up with a second wave file that's an exact copy of the one sent by the client through the socket.
I am currently working on a program of mine to try to send two csv files from my raspberry pi (client) to my laptop (server). In addition, I need to write two different sets of data to the two different csv files. The first one is raw data which will continue to write in data every 30 seconds and another is averaging of the raw data every 15 mins)
My first question is: Is it possible to do the above task? Or do I need to write two different servers and clients codes? (Refer to both codes below). Can I combine both of them? So that it can write two different data (raw and averaging) to two different csv file at the same time.
My second question is: How do I append new sets of data without rewriting the entire file (I tried append before and it duplicates the file data over and over again).
Client.py (This code currently only sends one csv file which is the raw data)
import time
import socket
TCP_IP = '192.168.1.105'
TCP_PORT = 5005
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
f = open('sensingdata.csv', 'rb')
print 'Sending...'
l = f.read(1024)
while (l):
print 'Sending...'
s.send(l)
l = f.read(1024)
print "Done Sending"
time.sleep(30)
Server.py
import socket
import sys
TCP_IP = ""
TCP_PORT = 5005
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(5)
while True:
conn, addr = s.accept()
f = open('sensing1.csv', 'wb')
print "Got connection from", addr
print "Receiving..."
l = conn.recv(1024)
while (l):
print "Receiving Data..."
f.write(l)
l = conn.recv(1024)
print "Done Receiving"
f.close()
conn.close()
Client2.py (This code is for the appending of averaging data)
import time
import socket
TCP_IP = '192.168.1.105'
TCP_PORT = 5005
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
g = open('average.csv', 'rb')
print 'Sending Averaging Data...'
l = f.read(1024)
while (l):
print 'Sending...'
s.send(l)
l = g.read(1024)
print "Done Sending"
time.sleep(900)
Server2.py
import socket
import sys
import csv
TCP_IP = ""
TCP_PORT = 5005
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(5)
while True:
conn, addr = s.accept()
g = open('average.csv', 'ab')
print "Got connection from", addr
print "Receiving Averaging Data..."
l = conn.recv(1024)
for rows in g:
while (l):
if row not in rows:
print "Receiving Averaging Data..."
g.write(l)
l = conn.recv(1024)
print "Done Receiving"
g.close()
conn.close()
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 :)