next I will write some code to run client and server. Here is :
in client_start.py
1 2 3 4 5 6 7
from client import Client if __name__ == "__main__": c = Client('localhost',7777) c.connect() c.send('hello') message = c.recv() print('message',message)
in server_start.py
1 2 3 4 5
from server import Server if __name__ == "__main__": s = Server(7777, listen = 1000) s.run()
Run server_start.py firstly and then run client_start.py. You will find both client and server print messages. Then client is shut down, but server is still running. Yup. Server should not shut down in order to supply services. And shut client down to close socket connection and save resources of server. These code runs perfectly. But we still should make some improvement. Server can server many clients. When it servers one client connection, it should server other connections and not be held by the former connection. Now multi-thread is considered.
in “run” function of Server in server.py
change run function and add a new function called “serviceWaiting”
Ok, done! Now server can server multi-clients in the same time. But only sending and receiving string is not enough for our applications. Sending and receiving objects should be considered.
Here we add two functions in client.py and server.py.
we should change a function in our former code:
1 2 3 4 5 6
defrecv(self, n= -1): if n == -1: returnstr(self.client.recv(self.bufsize),encoding="utf8") else: returnstr(self.client.recv(n),encoding="utf8")
then we should add two function for sending and receive objects
In sendObj(), first transform object to bytes and send the length of object. Then wait to receive “OK” message(string ‘Y’). If get OK message, then use sendall() function to send all bytes out. Then wait to receive another OK message. Here we use recv(1) to only get one char in receiving queue. We should not use recv to get more information which may not be used by sendObj() function.
In recvObj(), first receive the length of object. Then send OK message back. Receive bytes by fixed buffer each time. And receiv many times until we received all bytes of object. Then transform bytes to objects and send OK message back.
Ok. Now we should consider if the we can not connect server at first time. How do we solve this problem? The simplest idea is try many times until we connected server successfully.We should change connection() function.