Class 6 Lab 3 ‐ Test Communication - Justin-Boyd/Python-Class GitHub Wiki
Task 1: Server Socket Creation
Step 1
- In the PyCharm project created in L1, create a new Python file by right-clicking the projects folder, and selecting New > Python File. Name the file Server Message.
Step 2
- Import the socket module to the file.
import socket
Step 3
- Create a socket variable.
sock = socket.socket()
Step 4
- Bind the socket to accept connections from all IP addresses on port 4444.
sock.bind(("0.0.0.0", 45000))
Step 5
- Allow only one connection to the socket.
sock.listen(1)
Step 6
- Allow the server to accept connections, and save the connection object and the address to variables.
conn, addr = sock.accept()
Step 7
- Send a welcome message to the connected client.
conn.send("Welcome to the server!")
Step 8
- Encode the message sent to the client.
conn.send("Welcome to the server!".encode())
Step 9
- Accept a message from the client and print it.
print(conn.recv(2048).decode())
Step 10
sock.close()
Task 2: Client Socket Creation
Step 1
- Create a new Python file by right-clicking the projects folder, and selecting New > Python File. Name the file Client Message.
Step 2
- Import the socket module to the file.
import socket
Step 3
- Create a socket variable.
sock = socket.socket()
Step 4
- Connect the socket to the listener in the server.
sock.connect(("127.0.0.1", 45000))
Step 5
- Allow the client to receive the message from the server, and print it.
print(sock.recv(2048).decode())
Step 6
- Return a message to the server notifying it that the client received the message.
sock.send("Thanks!".encode())
Step 7
sock.close()
Step 8
- Execute the server script.
Step 9
- Execute the client script.
Step 10
- Notice the message the client received.
Step 11
- Notice the message the server received.
Final Code
Client Message
"""Lab Objective: Create a server socket and a client socket and enable them to communicate with each other."""
import socket
sock = socket.socket()
sock.connect(("127.0.0.1", 45000))
print(sock.recv(2048).decode())
sock.send("Thanks!".encode())
sock.close()
input("\nPress 'Enter' to exit the program")# prevents program from closing upon execution
Server Message
"""Lab Objective: Create a server socket and a client socket and enable them to communicate with each other."""
import socket
sock = socket.socket()
sock.bind(("0.0.0.0", 45000))
sock.listen(1)
conn, addr = sock.accept()
conn.send("Welcome to the server!".encode())
print(conn.recv(2048).decode())
sock.close()
input("\nPress 'Enter' to exit the program")# prevents program from closing upon execution