Sending string via socket (python)

后端 未结 3 568
予麋鹿
予麋鹿 2020-11-30 23:32

I have two scripts, Server.py and Client.py. I have two objectives in mind:

  1. To be able to send data again and again to server from client.
  2. To be ab
3条回答
  •  难免孤独
    2020-12-01 00:08

    client.py

    import socket
    
    s = socket.socket()
    s.connect(('127.0.0.1',12345))
    while True:
        str = raw_input("S: ")
        s.send(str.encode());
        if(str == "Bye" or str == "bye"):
            break
        print "N:",s.recv(1024).decode()
    s.close()
    

    server.py

    import socket
    
    s = socket.socket()
    port = 12345
    s.bind(('', port))
    s.listen(5)
    c, addr = s.accept()
    print "Socket Up and running with a connection from",addr
    while True:
        rcvdData = c.recv(1024).decode()
        print "S:",rcvdData
        sendData = raw_input("N: ")
        c.send(sendData.encode())
        if(sendData == "Bye" or sendData == "bye"):
            break
    c.close()
    

    This should be the code for a small prototype for the chatting app you wanted. Run both of them in separate terminals but then just check for the ports.

提交回复
热议问题