Video Chat App

Server Side Code (“Server.py”)

import socket, cv2, pickle,struct# ----->Socket Creation
server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#getting host ip
host_name = socket.gethostname()
host_ip = socket.gethostbyname(host_name)
#port as user input
port = int(input('Enter the port number----->'))
socket_address = (host_ip,port)
# ---->Socket binding
server_socket.bind(socket_address)
# ----->Socket listening
server_socket.listen(5)
print("listening at: ",socket_address)
# ------>Socket Accepting Clients
while True:
client_socket,addr = server_socket.accept()
print('got request from: ',addr)
if client_socket:
vid = cv2.VideoCapture(0)

while(vid.isOpened()):
img,frame = vid.read()
a = pickle.dumps(frame)
message = struct.pack("Q",len(a))+a
client_socket.sendall(message)

cv2.imshow('server cam',frame)
key = cv2.waitKey(1) & 0xFF
if key ==ord('q'):
client_socket.close()

Client Side Code (“Client.py”)

import socket,cv2, pickle,struct# ------>create socket
client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#-------> Getting host ip
host_name = socket.gethostname()
host_ip = socket.gethostbyname(host_name)
port=int(input("Enter port number--->"))
#-------> socket Connection with server
client_socket.connect((host_ip,port))
data = b""
payload_size = struct.calcsize("Q")
while True:
while len(data) < payload_size:
packet = client_socket.recv(4*1024) # 4K
if not packet: break
data+=packet
packed_msg_size = data[:payload_size]
data = data[payload_size:]
msg_size = struct.unpack("Q",packed_msg_size)[0]

while len(data) < msg_size:
data += client_socket.recv(4*1024)
frame_data = data[:msg_size]
data = data[msg_size:]
frame = pickle.loads(frame_data)
cv2.imshow("client cam",frame)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
client_socket.close()

Tushar jain

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store