Python Server-Client Communication with each other

1.4k views Asked by At

I am trying to modify a tcp/ip server-client communication. Only the server can communicate with the client. I am trying to find an easy a way to send a message back to the server. Not a chat !! Just a server which will send data to a client and receive data from the client.

I am using this example :

Server:

    host="my_ip"
    port=4446                  
    from socket import *              
    s=socket()
    s.bind((host,port))                 
    s.listen(1)                         
    print "Listening for connections.. "
    q,addr=s.accept()               
    var = 1
    while var == 1 :
         data=raw_input("Enter data to be send:  ")  
         q.send(data)  
    s.close()

Client:

    host="my_ip"
    port=4446 
    from socket import *
    s=socket(AF_INET, SOCK_STREAM)
    s.connect((host,port))
    var = 1
    while var == 1 :  
         msg=s.recv(1024)
         print "Message from server : " + msg
         #response = "Message delivered"   # Response to be send 
         #s.sendto(response(host,port)) 
    s.close()
2

There are 2 answers

1
Monkeyanator On

Python actual has a built in class to make your life a bit easier. http://docs.python.org/2/library/socketserver.html. I'm not sure I understand the second part of your question however; you can simply send data back to the server in the same way you had the server send data to the client.

0
Dylan On

Use sock.sendall(). Also, you shouldn't just name a var "var" as it doesn't describe what it does. I would create a boolean instead and name it something like, "isListening" or "isSending".