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 :)
Related
I start the server, then the client, the server gets the data and the client does not get a response, crashes
server
import pygame, socket, time
pygame.init()
main_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
main_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
main_socket.bind(("localhost", 10000))
main_socket.setblocking(0)
main_socket.listen(5)
players_sockets = []
while True:
try:
new_socket, addr = main_socket.accept()
print("Connect", addr)
new_socket.setblocking(0)
players_sockets.append(new_socket)
except:
pass
for i in players_sockets:
try:
data = i.recv(1024)
data = data.decode()
except:
pass
for i in players_sockets:
try:
i.send("server data").encode()
except:
players_sockets.remove(i)
print("Disconnect")
i.close()
time.sleep(1)
client
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.connect(("localhost", 10000))
while True:
sock.send("Command".encode())
data = sock.recv(1024)
data = data.decode()
print(data)
error:
" data = sock.recv(1024)
ConnectionAbortedError: [WinError 10053] The program on your host computer has broken an established connection."
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 creating simple server client architecture using pickle. When I receive data and print it, first number disaapear, why? how can I avoid this?
for example: ({2,2,4}, {3,4}) - > ({2,4}, {3,4})
server code:
import pickle
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print ("conn info: ", conn)
objrcv = pickle.loads(conn.recv(10024))
print("conn recv: ", objrcv)
print("conn from: ", addr)
print(objrcv)
client code
import socket
import pickle
name = 'name'
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
data = pickle.dumps(name)
s.connect((TCP_IP, TCP_PORT))
# #s.send(data) #powitalne info, dane gracza
def wyslij_dane(my_array): #sending data
data = pickle.dumps(my_array)
if data[0] != 0: # pierwszy argument odpowiedzialny za poddanie sie
print('before send')
s.send(data)
print('after send') #just to control
#data_recv = s.recv(BUFFER_SIZE)
#print("received data:", data_recv)
def rozlacz():#disconnecting
s.close()
wyslij_dane(({2,2,4}, {3,4}))
wyslij_dane({2,2,433})
wyslij_dane(0)
rozlacz()
server output:
conn info: ...
conn recv: ({2, 4}, {3, 4})
conn from: ('127.0.0.1', 51876)
({2, 4}, {3, 4})
And another question is: What can I do to handle all sending data (all call wyslij_dane() funcions)?
"{}" means you are using a set. In a set every item exists only once. Instead you can use a list with these -> "[]" or a tupel -> "()"
So
wyslij_dane(({2,2,4}, {3,4}))
becomes
wyslij_dane(([2,2,4], [3,4]))
and so on.
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.
Someone can add to my Example under, the code that define the Client socket try to connect to the server for 2 seconds please ?
I read about that and i don't successful to do that, because of that i ask for an example.
Example:
Client:
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 7777
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()
print "received data:", data
Server:
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 7777
BUFFER_SIZE = 20
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
print "received data:", data
conn.send(data)
conn.close()
Thank you.
Instead of having two separate python files, you can have a single file but put the server and client in separate threads. sys.stdout.write is used instead of print due some concurrency issue with print being buffered (it mixes strings).
import threading
import socket
import sys
class socket_server(threading.Thread):
TCP_IP = "127.0.0.1"
TCP_PORT = 7777
BUFFER_SIZE = 20
daemon = True
def run(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((self.TCP_IP, self.TCP_PORT))
s.listen(1)
conn, addr = s.accept()
(ip, port) = addr
sys.stdout.write("%s connection address: IP %s on Port %d\n" % (self.__class__.__name__, ip, port))
data = True
while data:
data = conn.recv(self.BUFFER_SIZE)
if data:
sys.stdout.write("%s received data: %s\n" % (self.__class__.__name__, data))
send_data = data.upper()
sys.stdout.write("%s sending data: %s\n" % (self.__class__.__name__, send_data))
conn.send(send_data)
conn.close()
class socket_client(threading.Thread):
TCP_IP = "127.0.0.1"
TCP_PORT = 7777
BUFFER_SIZE = 1024
TIMEOUT = 2.0
MESSAGE = "Hello, World!"
def run(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(self.TIMEOUT)
s.connect((self.TCP_IP, self.TCP_PORT))
sys.stdout.write("%s sending data: %s\n" % (self.__class__.__name__, self.MESSAGE))
s.send(self.MESSAGE)
data = s.recv(self.BUFFER_SIZE)
s.close()
if data:
sys.stdout.write("%s received data: %s\n" % (self.__class__.__name__, data))
server = socket_server()
client = socket_client()
server.start()
client.start()