As a network programmer in HD Sdn Bhd you are required to create a simple program to enable communication between a client and a server Your program should have the following featuresi Socket connecti
Here is a sample code in Python for a simple client-server communication program:
Server Side:
import socket
set the host and port number
HOST = '127.0.0.1' PORT = 9000
create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
bind the socket object to a specific host and port number
server_socket.bind((HOST, PORT))
listen for incoming connections
server_socket.listen(1)
accept the client connection
client_socket, address = server_socket.accept()
receive data from client and send response back
while True: data = client_socket.recv(1024).decode() if not data: break elif data == 'Exit': client_socket.sendall('Goodbye!'.encode()) break else: client_socket.sendall(('Received: ' + data).encode())
close the socket connection
client_socket.close() server_socket.close()
Client Side:
import socket
set the host and port number
HOST = '127.0.0.1' PORT = 9000
create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connect to the server
client_socket.connect((HOST, PORT))
send message to the server
message = input('Enter message: ') client_socket.sendall(message.encode())
receive response from the server
response = client_socket.recv(1024).decode() print(response)
close the socket connection
client_socket.close()
Note: This is just a basic example and does not include error handling for all possible scenarios. It is important to implement proper error handling and exception catching in a real-world application
原文地址: http://www.cveoy.top/t/topic/fj5Z 著作权归作者所有。请勿转载和采集!