-1

I wanted to create a software that can send video through socket programming. I can send 1 video at a time but when I want to send more than 2, it is stuck.

Below is the server code:

import socket
import os

IP = "127.0.0.1"
PORT = 4456
SIZE = 1024
FORMAT = "utf"
SERVER_FOLDER = "video_folder"


def main():
    print("[STARTING] Server is starting.\n")
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((IP, PORT))
    server.listen()
    print("[LISTENING] Server is waiting for clients.")

    conn, addr = server.accept()
    print(f"[NEW CONNECTION] {addr} connected.\n")

    """ Receiving the folder_name """
    folder_name = conn.recv(SIZE).decode(FORMAT)

    """ Creating the folder """
    folder_path = os.path.join(SERVER_FOLDER, folder_name)
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)
        conn.send(f"Folder ({folder_name}) created.".encode(FORMAT))
    else:
        conn.send(f"Folder ({folder_name}) already exists.".encode(FORMAT))

    """ Receiving files """
    while True:
        msg = conn.recv(SIZE).decode(FORMAT)

        """ Recv the file name """
        print(f"[CLIENT] Received the filename: {msg}.")
        file_path = os.path.join(folder_path, msg)
        file = open(file_path, "wb")
        conn.send(f"{file_path} filename received.".encode(FORMAT))

        while True:
            msg = conn.recv(SIZE)  # it stuck here once the msg become nothing need help
            if not msg:
                conn.send("The data is saved.".encode(FORMAT))
                break

            file.write(msg)
            print('.', end='', flush=True)

        if not msg: break

    file.close()
    print("\ndone.")


def test():
    while True:
        x = "World"
        print("morning")
        while True:
            print("Hello" + x)
            break


if __name__ == "__main__":
    main()

Below is the client code:

import socket
import os

IP = "127.0.0.1"
PORT = 4456
SIZE = 1024
FORMAT = "utf"
CLIENT_FOLDER = "C:/Users/wende/OneDrive/Desktop/client_folder"


def main():
    """ Staring a TCP socket. """
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect((IP, PORT))

    """ Folder path """
    path = os.path.join(CLIENT_FOLDER, "files")
    folder_name = path.split("/")[-1]

    """ Sending the folder name """
    msg = f"{folder_name}"
    print(f"[CLIENT] Sending folder name: {folder_name}")
    client.send(msg.encode(FORMAT))

    """ Receiving the reply from the server """
    msg = client.recv(SIZE).decode(FORMAT)
    print(f"[SERVER] {msg}\n")

    """ Sending files """
    files = sorted(os.listdir(path))

    for file_name in files:
        """ Send the file name """
        print(f"[CLIENT] Sending file name: {file_name}")
        client.send(file_name.encode(FORMAT))

        """ Recv the reply from the server """
        msg = client.recv(SIZE).decode(FORMAT)
        print(f"[SERVER] {msg}")

        """ Send the data """
        file = open(os.path.join(path, file_name), "rb")
        file_data = file.read()
        client.send(file_data)
        print("Sending File...")
        msg = client.recv(SIZE).decode(FORMAT)
        print(f"[SERVER] {msg}")


if __name__ == "__main__":
    main()

I have found out where the code is stuck, but I have no idea why it pauses there for no reason.

The problem I found is I keep loop the received at the server and once the received part is NULL then the loop will stop, but the problem I faced is once the received part is NULL, it cannot jump to the next if statement to check. I try transfer 1 video is no problem at all.

How can I solve this?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • See [Sending multiple files through a TCP socket](https://stackoverflow.com/a/59692611/235698). send/recv not are 1:1, meaning a `send` of say 1000 bytes will not result in a matching `recv` of 1000 bytes. The only guarantee is the bytes will be received in the order sent. Design a protocol for the byte stream as mentioned in the link. – Mark Tolonen Dec 10 '22 at 19:34
  • tried not working for me the problem still remain the same once one video is sent then it stuck and cannot proceed to the next video. – Wendell Wong Dec 19 '22 at 13:41
  • After reading that link what did you try? – Mark Tolonen Dec 19 '22 at 17:48
  • i copy the code and paste then i try to perform the same task that is access to a folder that has some videos and read them 1 by 1 then send 1 by 1. – Wendell Wong Dec 21 '22 at 09:03

1 Answers1

-1

The solution is here: Sending a file over TCP sockets in Python You need to put this line in the client code

client.shutdown(socket.SHUT_WR) 

after

client.send(file_data)

IMO: Better to use async / await words to do your chat asynchronously. In current realization when you receive one message from a first client the second going to wait until the first will finish. I think it will help you Simplest async/await example possible in Python

iYasha
  • 61
  • 4
  • Thank you for reply. But the problem is I only tried working on 1 client only and the code stuck. Also the async / await I not very sure but based on my understanding after reading the link you sent to me is more like a where to interrupt the function. Which i dont really understand will it help to solve my problem. – Wendell Wong Dec 10 '22 at 09:22
  • There is your solution: https://stackoverflow.com/questions/27241804/sending-a-file-over-tcp-sockets-in-python You need to put this line "client.shutdown(socket.SHUT_WR)" after client.send(file_data) – iYasha Dec 10 '22 at 10:06
  • Thanks, iYasha my problem did solve but it creates another problem, which is after sending 1 video and it exit the loop now when the client want to send another request it reject because it said "BrokenPipeError: [WinError 10058] A request to send or receive data was disallowed because the socket had already been shut down in that direction with a previous shutdown call" – Wendell Wong Dec 10 '22 at 10:46
  • You can add the loop inside your client code and reconnect to the socket after you sent a video – iYasha Dec 10 '22 at 10:51
  • Already did a loop in the beginning, now I want to try reconnecting back the socket after shutdown but google doesn't have answer for me, maybe my keyword is wrong but i really can't solve it. – Wendell Wong Dec 10 '22 at 14:58