Voice call app crashes after joining Voice Call - python

I built a voice call app and for some reason when I join the vc it just crashes the app. No errors, nothing. It appears that is it not connecting to the server even tho the connection details are correct but I think there is something else going on. Pls Help!
Here is the Server Code:
def on_server_stop():
log(consoleLog="Stopping Vc Server")
sys.exit()
host = '0.0.0.0'
port = 5000
server = socket.socket()
server.bind((host, port))
server.listen()
log(consoleLog='Voice call server started and online!')
clientsInVC = []
def handleVC(fromConnection):
log(consoleLog="User conected to VC server.")
while True:
try:
data = fromConnection.recv(4096)
for client in clientsInVC:
if client != fromConnection:
client.send(data)
except:
client.close()
clientsInVC.remove(conn)
while True:
conn, addr = server.accept()
clientsInVC.append(conn)
thread = threading.Thread(target=handleVC, args=(conn, ))
thread.start()
Here is the Client Code:
import pyaudio
import socket
import threading
def JOINVC():
print("started vc")
vcclient = socket.socket()
host = "127.0.0.1"
port = 5000
vcclient.connect((host, port))
p = pyaudio.PyAudio()
Format = pyaudio.paInt16
Chunks = 1024 * 4
Channels = 1
Rate = 44100
inputStream = p.open(format=Format, channels=Channels, rate=Rate, input=True, frames_per_buffer= Chunks)
outputStream = p.open(format=Format, channels=Channels, rate=Rate, output=True, frames_per_buffer= Chunks)
def sendData():
while True:
try:
data = inputStream
vcclient.send(data)
except:
break
inputStream.close()
def recive():
while True:
try:
data = inputStream.read(Chunks)
outputStream.write(data)
except:
break
outputStream.close()
sendThread = threading.Thread(target = sendData)
sendThread.start()
reciveThread = threading.Thread(target= recive)
reciveThread.start()

Related

How to send request disconnect from server to all clients and server still live (python socket)

When I disconnect all clients in server, server doesn't continue live. How can I do for living server
import socket, threading, tkinter
Server
import socket, threading, tkinter
import time
def sendDisconnectAll(my_clients):
for client in my_clients:
conn = client[0]
conn.sendall('Disconnect'.encode('utf8'))
conn.close()
def handle_client(conn, addr):
while True:
try:
request_from_clients = conn.recv(1024).decode('utf8') #sample request
print(request_from_clients)
if request_from_clients == 'SignIn':
conn.sendall('Accept Sign in'.encode('utf8'))
except:
print('Client has been shutdown')
break
my_clients = []
def live_server():
global thr
global s
while True:
try:
conn, addr = s.accept()
my_clients.append((conn, addr))
thr = threading.Thread(target=handle_client, args=(conn, addr))
thr.daemon = True
thr.start()
except:
print("Error")
HOST = '127.0.0.1'
PORT = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen()
print('HOST: ', HOST)
print('PORT: ', PORT)
thr = threading.Thread(target=live_server)
thr.daemon = True
thr.start()
count_time = time.time()
while True:
now = time.time()
if (int(now - count_time) + 1) % 10 == 0: #Disconnect all clients after 10 seconds
count_time = now
request = 'Disconnect'
print('Disconnect all')
sendDisconnectAll(my_clients)
Clients
import socket, threading
import tkinter as tk
from tkinter import *
def signIn():
global client
request = 'SignIn'
try:
client.sendall(request.encode('utf8'))
client.recv(1024).decode('utf8')
except:
print('Server has been shutdown')
IP = input("Enter IP: ")
PORT = input("Enter PORT: ")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect((IP, int(PORT)))
except:
print("Can't connect to server")
client.close()
def live_client():
global client
while True:
print(client.recv(1024).decode('utf8'))
thr = threading.Thread(target=live_client)
thr.daemon = True
thr.start()
app = Tk()
app.title('CLIENT')
but_connect = tk.Button(app, text="SIGN IN",
width=20, command=signIn)
but_connect.pack(pady=6)
app.mainloop()
Thank you!
The problem is that you only add clients to the my_clients list. Let's look what happens in server:
server starts
it receives one client an adds it to my_clients
on next disconnect all operation the socket for that client is closed, but the client remains on the list
on the following disconnect all operation, the main thread of the server tries to write to a closed socket and raises an exception
as all other threads are daemonic, the application ends.
You must clear the my_clients list after closing all the client sockets:
def sendDisconnectAll(my_clients):
for client in my_clients:
conn = client[0]
conn.sendall('Disconnect'.encode('utf8'))
conn.close()
my_clients.clear()
Beware: I did not look at client code...

Getting a TimeOut Error when trying to run a python code that transfers files from EC2 to Local

This is the code on the AWS EC2 instance:
import socket
from threading import Thread
from socketserver import ThreadingMixIn
TCP_IP = 'localhost'
TCP_PORT = 9001
BUFFER_SIZE = 1024
class ClientThread(Thread):
def __init__(self,ip,port,sock):
Thread.__init__(self)
self.ip = ip
self.port = port
self.sock = sock
print (" New thread started for "+ip+":"+str(port))
def run(self):
filename='mytext.txt'
f = open(filename,'rb')
while True:
l = f.read(BUFFER_SIZE)
while (l):
self.sock.send(l)
#print('Sent ',repr(l))
l = f.read(BUFFER_SIZE)
if not l:
f.close()
self.sock.close()
break
tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpsock.bind((TCP_IP, TCP_PORT))
threads = []
while True:
tcpsock.listen(5)
print ("Waiting for incoming connections...")
(conn, (ip,port)) = tcpsock.accept()
print ('Got connection from ', (ip,port))
newthread = ClientThread(ip,port,conn)
newthread.start()
threads.append(newthread)
for t in threads:
t.join()
And this is the code on my local machine:
import socket
import time
#TCP_IP = 'localhost'
TCP_IP = 'ip-ec2-instance'
TCP_PORT = 60001
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
clock_start = time.clock()
time_start = time.time()
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:
f.close()
print ('file close()')
break
# write data to a file
f.write(data)
print('Successfully get the file')
s.close()
print('connection closed')
clock_end = time.clock()
time_end = time.time()
duration_clock = clock_end - clock_start
print ('clock: start = ',clock_start, ' end = ',clock_end)
print ('clock: duration_clock = ', duration_clock)
duration_time = time_end - time_start
print ('time: start = ',time_start, ' end = ',time_end)
print ('time: duration_time = ', duration_time)
Now, the code on the EC2 instance seems to run fine and waits for a connection, but the code on my local machine gives me the error mentioned below when I try running it with the public IP of the EC2 instance:
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I can't figure out how to fix this.

Python Sockets Port forwarding

So I port forwarded my ip so that my friends can test if my stuff works
And I have a simple server that is hosted on the internal ip
import socket
import threading
class Server:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connections = []
def __init__(self, ip="0.0.0.0", port=5555):
self.sock.bind((ip, port))
self.sock.listen(1)
def handler(self, c, a):
while True:
data = c.recv(4096)
for connection in self.connections:
connection.send(data)
if not data:
print(str(a[0]) + ":" + str(a[1]), "disconnected")
self.connections.remove(c)
c.close()
break
def run(self):
while True:
c, a = self.sock.accept()
rThread = threading.Thread(target=self.handler, args=(c, a))
rThread.daemon = True
rThread.start()
self.connections.append(c)
print(str(a[0]) + ":" + str(a[1]), "connected")
host = Server("192.168.x.xxx", 6667)
print("Server status: Running")
host.run()
And a simple client module that I attempted to pass the public ip to
import socket
import pickle
import threading
import pyaudio
import numpy as np
class Client():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def __init__(self, address):
threading.Thread.__init__(self)
self.sock.connect((address, 6667))
def run(self, id):
RATE = 16000
CHUNK = 256
self.id = id
p = pyaudio.PyAudio()
player = p.open(format=pyaudio.paInt16, channels=1, rate=RATE, output=True, frames_per_buffer=CHUNK)
while True:
data = self.sock.recv(4096)
data = pickle.loads(data)
if data[0] != self.id:
if not data:
break
player.write(np.fromstring(data[1],dtype=np.int16),CHUNK)
def sendMsg(self, data, id):
data1 = [id, data]
self.sock.send(pickle.dumps(data1))
The client does not connect to the server when I try to give it the public address
print("Connecting to server")
cli = Client("91.242.xxx.xxx")
rThread = threading.Thread(target=cli.run, args=(id,))
rThread.daemon = True
rThread.start()
print("Connected to server")
The only thing that outputs is Connecting to server
I am not sure what I am doing wrong or what to do to fix this
My ISP uses CGNat and I just had to call them to tell them that I need a public IP and they gladly did it for me.

Streaming voice between two endpoint

everyone, i'm using a python code to Stream voice between to endpoints.
the code doesn't give me an error i just stuck at some point i don't now why
what im trying to achieve is i want to speak from one endpoint and hear my voice at the other end point
i don't want to use TCP i want to use UDP so i can avoid the latency
the receiver cod
import socket
import pyaudio
import select
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 4096
audio = pyaudio.PyAudio()
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # UDP
sock.connect(("172.20.10.6", 5555))
stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, output=True, frames_per_buffer=CHUNK)
#while True :
#print("Enter a UDP M\n")
#MESSAGE = input("")
#sock.sendto(MESSAGE.encode('utf-8'), (UDP_IP, UDP_PORT))
try:
while True:
data = sock.recvfrom(CHUNK)
stream.write(data)
except KeyboardInterrupt:
pass
print('Shutting down')
sock.close()
stream.close()
audio.terminate()
the sender
import pyaudio
import socket
import select
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 4096
audio = pyaudio.PyAudio()
UDP_IP = "0.0.0.0"
UDP_PORT = 5555
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM , socket.IPPROTO_UDP) # UDP
sock.bind((UDP_IP, UDP_PORT))
def callback(in_data, frame_count, time_info, status):
for s in read_list[1:]:
print (s)
s.send(in_data)
return (None, pyaudio.paContinue)
stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK, stream_callback=callback)
# stream.start_stream()
read_list = [sock]
print ("recording...")
try:
while True:
print ("1")
readable, writable, errored = select.select(read_list, [], [])
print ("2")
for s in readable:
if s is sock:
(clientsocket, address) = sock.accept()
read_list.append(clientsocket)
print ("Connection from", address)
else:
data = sock.recvfrom(1024)
if not data:
read_list.remove(s)
except KeyboardInterrupt:
pass
print ("finished recording")
serversocket.close()
# stop Recording
stream.stop_stream()
stream.close()
audio.terminate()
as you can see the code stuck at where i print the number 2 it doesn't print it
the below code is to a UDP connection that only Send a String
import socket
UDP_IP = "172.20.10.6"
UDP_PORT = 5005
MESSAGE = "Hello, World!"
print ("UDP target IP:", UDP_IP)
print ("UDP target port:", UDP_PORT)
print ("message:", MESSAGE)
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # UDP
while True :
print("Enter a UDP M\n")
MESSAGE = input("")
sock.sendto(MESSAGE.encode('utf-8'), (UDP_IP, UDP_PORT))
import socket
UDP_IP = "172.20.10.6"
UDP_PORT = 5005
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print ("received message:", data)

Python sending files over socket

I want to do a file dispatcher, the server is loaded with a list of files and then sends them one by one with each client request.
The idea is to distribute the processing of many files between 5 servers.
How could I call the ClientThread class with each client connection?
The script is only programmed to send the same file to each client request, what I want is to send a different file from a list of files in each client request.
Server.py
import socket
from threading import Thread
from socketserver import ThreadingMixIn
TCP_IP = '10.30.16.28'
TCP_PORT = 1006
BUFFER_SIZE = 1024
class ClientThread(Thread):
def __init__(self,ip,port,sock):
Thread.__init__(self)
self.ip = ip
self.port = port
self.sock = sock
print(" New thread started for "+ip+":"+str(port))
def run(self):
filename='log.VW.20170214a.log'
f = open(filename,'rb')
while True:
l = f.read(BUFFER_SIZE)
while (l):
self.sock.send(l)
l = f.read(BUFFER_SIZE)
if not l:
f.close()
self.sock.close()
break
tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpsock.bind((TCP_IP, TCP_PORT))
threads = []
with open("list.txt") as x: #File containing files list
lines=x.read().splitlines()
while True:
tcpsock.listen(5)
print("Waiting for incoming connections...")
(conn, (ip,port)) = tcpsock.accept()
print('Got connection from ', (ip,port))
newthread = ClientThread(ip,port,conn)
newthread.start()
threads.append(newthread)
for t in threads:
t.join()
Client.py
import socket
TCP_IP = '10.30.16.28'
TCP_PORT = 1006
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
with open('received_file', 'wb') as f:
print('file opened')
while True:
data = s.recv(BUFFER_SIZE)
if not data:
f.close()
print('file close()')
break
f.write(data)
print('Successfully get the file')
s.close()
print('connection closed')
I don't see what this has to do with threading or ports or anything like that. Change this:
def __init__(self,ip,port,sock,fname):
Thread.__init__(self)
self.ip = ip
self.port = port
self.sock = sock
self.fname = fname
print(" New thread started for "+ip+":"+str(port))
def run(self):
f = open(self.fname,'rb')
And when you serve:
with open("list.txt") as x: #File containing files list
lines=iter(x.read().splitlines())
and finally:
newthread = ClientThread(ip,port,conn,lines.next().strip())
lines.next() will throw a StopIteration exception when done, so you have to handle that.

Categories