Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
refused connection
#1
I am trying to take pics with the webcam and send them to the client via socket.
I am not sure why, the server, which I always start first, stops almost immediately and the following error shows:


Error:
Traceback (most recent call last): File "C:/Users/PycharmProjects/client-server/server.py", line 14, in <module> s.connect((host, port)) ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
here are both codes
SERVER
import cv2
import time
import socket
from PIL import Image
import pickle
import struct


host = socket.gethostname()
port = 8485


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.listen(5)
conn, address = s.accept()

print("server started...")

capture = cv2.VideoCapture(0)
capture.set(3, 640)
capture.set(4, 480)
img_counter = 0
#frame_set = []
start_time = time.time()

while True:
    ret, frame = capture.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('frame', gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    if time.time() - start_time >= 1: # how often (secs) are pics taken
        filename = "opencv_frame_{}.png".format(img_counter)
        #cv2.imwrite(filename, frame)
        data = pickle.dumps(frame, 0)
        size = len(data)
        print("{} written!".format(img_counter))
        start_time = time.time()
        s.sendall(struct.pack(">L", size) + data)
        img_counter += 1

capture.release()
CLIENT
import socket
import cv2
import pickle
import struct


host =  socket.gethostname()
port = 8485

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))

conn,addr=s.accept()

data = b""
payload_size = struct.calcsize(">L")
print("payload_size: {}".format(payload_size))
while True:
    while len(data) < payload_size:
        print("Recv: {}".format(len(data)))
        data += conn.recv(4096)

    print("Done Recv: {}".format(len(data)))
    packed_msg_size = data[:payload_size]
    data = data[payload_size:]
    msg_size = struct.unpack(">L", packed_msg_size)[0]
    print("msg_size: {}".format(msg_size))
    while len(data) < msg_size:
        data += conn.recv(4096)
    frame_data = data[:msg_size]
    data = data[msg_size:]

    frame=pickle.loads(frame_data, fix_imports=True, encoding="bytes")
    frame = cv2.imdecode(frame, cv2.IMREAD_COLOR)
    cv2.imshow('ImageWindow',frame)
    cv2.waitKey(1)
Reply
#2
The server should not call s.connect((host, port)) but s.bind((host, port)).

Also I recommend that before calling bind() the server configures the socket with
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
this is useful if you start the server several times and you don't want to receive the error address already in use.
Reply
#3
thank you.

I had to change a few things and it looks like that is working better than before,
but now I am getting a new type of error on the client side which is very strange since it has no winerror number:
Error:
Traceback (most recent call last): File "C:/Users/PycharmProjects/client-server/client.py", line 37, in <module> frame = cv2.imdecode(frame, cv2.IMREAD_COLOR) cv2.error: OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:728: error: (-215:Assertion failed) buf.checkVector(1, CV_8U) > 0 in function 'cv::imdecode_'
here are again both server and client codes:
I am including it in the code window by clicking "insert python" as usual, but this time I am not able to see it inside the code space. I am not sure why.
SERVER

import cv2
import time
import socket
from PIL import Image
import pickle
import struct


host = "127.0.0.1"
port = 5000


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(5)



print("server started...")

capture = cv2.VideoCapture(0)
capture.set(3, 640)
capture.set(4, 480)
img_counter = 0
#frame_set = []
start_time = time.time()

while True:
    conn, address = s.accept()
    ret, frame = capture.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('frame', gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    if time.time() - start_time >= 1: # how often (secs) are pics taken
        filename = "opencv_frame_{}.png".format(img_counter)
        cv2.imwrite(filename, frame)
        data = pickle.dumps(frame, 0)
        size = len(data)
        print("{} written!".format(img_counter))
        start_time = time.time()
        conn.sendall(struct.pack(">L", size) + data)
        img_counter += 1

capture.release()
CLIENT

import socket
from typing import Any, Union

import cv2
import pickle
import struct


host = "127.0.0.1"
port = 5000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))


data = b""
payload_size = struct.calcsize(">L")
print("payload_size: {}".format(payload_size))


while True:

    while len(data) < payload_size:
        print("Recv: {}".format(len(data)))
        data += s.recv(4096)

    print("Done Recv: {}".format(len(data)))
    packed_msg_size = data[:payload_size]
    data = data[payload_size:]
    msg_size = struct.unpack(">L", packed_msg_size)[0]
    print("msg_size: {}".format(msg_size))
    while len(data) < msg_size:
        data += s.recv(4096)
    frame_data: Union[Union[int, bytes], Any] = data[:msg_size]
    data = data[msg_size:]
    frame=pickle.loads(frame_data, fix_imports=True, encoding="bytes")
    frame = cv2.imdecode(frame, cv2.IMREAD_COLOR)
    cv2.imshow('ImageWindow',frame)
    cv2.waitKey(1)
Reply
#4
This is no longer a network error. Unfortunately, I don't know the cv2 package so I cannot help you. You could perhaps experiment with the data that you're sending to cv2.imdecode(), create a minimal example with the bug (you don't need networking code for this) and start a new thread with a different title to attract helpers who know cv2.
Reply
#5
well, if I get rid of line 37 on the client side, I get no error but the loop stops at the first image.
Does that tell you anything?
Reply
#6
cv2.waitKey() is supposed to wait indefinitely. It could be this, but again I won't answer more about cv2 because it is meaningless to give advice about a library that one doesn't know.
Reply
#7
I honestly don't think that the problem now is cv2.
As I said in my previous reply, I got rid of line 37 and
I don't get a single error.
However, the iteration stops after the first picture, so I think
it must be something that prevents the while loop to iterate indefinitely,
I just can't figure out what.
Are you 100% positive that the problem I'm facing has to do with cv2 ?
Reply
#8
mcgrim Wrote:Are you 100% positive that the problem I'm facing has to do with cv2 ?
No, not at all. You need to investigate why the loop never exits. First thing it is a while True loop, so how do you expect it to exit? Also the s.recv(4096) is potentially blocking if there is nothing to read on the socket. The best thing to do is to add print or logging statements in the loop until you find which statements are actually executed.
Reply
#9
i don't want the while loop to exit, I want it to keep running until I press 'q'.
But somehow it stops after the 1st pic is taken.
The client actually receives the image, as a matter of fact, the only pic taken by the server,
is automatically displayed by the client.
All I want to know is why it stops and does not continue.
Reply
#10
mcgrim Wrote:All I want to know is why it stops and does not continue
You can find this out by adding print statements until one of them is not executed. Another solution is to use a debugger or a tracing module.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Machine actively refused it. External IP only ramboahoe 1 3,385 Mar-28-2020, 12:46 AM
Last Post: ramboahoe
  No connection could be made becouse the target machine actively refused it. GottaAimHigherPal 1 2,746 Oct-18-2018, 01:59 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020