s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname('localhost')
port = 5150
s.connect((host, port))
The client code uses the gethostbyname() method to find the connection information to the
server, based on the server’s host name. Since the server is running on the same system, you use the
special localhost host name.
The connect() method uses a tuple value of the host and port number to request the connection
with the server. If the connection fails, it returns an exception that you can catch.
Once the connection is established, you can use the send() and recv() methods to send and
receive byte streams. Just as in the server program, when the connection is terminated, you want to
use the close() method to properly end the session.
Try It Yourself: Create a Python Client Program
Follow these steps to create a Python client program that can communicate with the
server program you just created:
- Create the file script2004.py in the folder for this hour.
- Open the script2004.py file in a text editor and enter the code shown here:
Click here to view code image
1: #!/usr/bin/python3
2:
3: import socket
4: server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
5: host = socket.gethostbyname('localhost')
6: port = 5150
7:
8: server.connect((host, port))
9: data = server.recv(1024)
10: print(bytes.decode(data))
11: while True:
12: data = input('Enter text to send:')
13: server.send(str.encode(data))
14: data = server.recv(1024)
15: print('Received from server:', bytes.decode(data))
16: if (bytes.decode(data) == 'exit'):
17: break
18: print('Closing connection')
19: server.close() - Save the file.
The script2004.py code runs through the standard methods to create the socket
and connect to the remote server (lines 4 through 8). It then listens for the welcome
message from the server (line 9) and displays the message when it’s received (line
10).
After that, the client goes into an endless while loop, requesting a text string from the
user and sending it to the server (line 13). It listens for the response from the server
(line 14) and prints it on the command line. If the response from the server is exit,
the client closes the connection.