client and server receive and send only once

101 Views Asked by At

I wrote server and client and it seems that they are communicating only once. I tried a few ways to fix it but no luck . I tried to put '\n' at the end of the string but no change. can someone help? server code :

    # server
    import socket

    SERVER_IP = '0.0.0.0'
    DEST_PORT = 1731

    server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

    server_socket.bind((SERVER_IP,DEST_PORT))
    server_socket.listen(1)

    client_socket,address=server_socket.accept()

    for i in range(2):
        data = client_socket.recv(512).decode()
        client_socket.sendall(("hello"+data+'\n').encode())
        data1 = client_socket.recv(512).decode()
        print(data1)

    client_socket.close()
    server_socket.close()



    #client
    import socket

    HOST_IP = '127.0.0.1'
    DEST_PORT = 1731


    my_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

    my_socket.connect((HOST_IP,DEST_PORT))
    user_msg = input("Enter massage:")
    for i in range(2):
        my_socket.sendall(user_msg.encode())
        data = my_socket.recv(512).decode()
        print(data)
        my_socket.sendall("hiii\n".encode())

    my_socket.close()
1

There are 1 best solutions below

0
Masklinn On

Works for me, but since you're getting the input outside the client loop, the two iterations are instantaenous:

  • the client sends the input
  • the server replies with the input
  • the client sends its last message and loops around
  • the server receives and print the message and loops around
  • the client re-sends the input
  • the client replies with the same input it got again
  • the client sends its last message and exits
  • the server prints the last message and exits

This is pretty clear when printing clearer messages (the prefix is whichever side is printing):

Enter massage:test message <- client sends this, server replies with "ping <message>"
[client] ping test message <- client prints response, sends final message and loops around
[server] pong <- server prints second message it got, loops around
[client] ping test message <- client prints response it got from server bouncing message again
[client] stop <- client exits
[server] pong <- server gets second message of loop
[server] stop <- and exits