import socket
import sys
import threading
import time
class EchoServer():
def __init__(self, server_host, server_port):
self.server_host = server_host
self.server_port = server_port
self.server_backlog = 1
self.start()
def start(self):
# Initialize server socket on which to listen for connections
try:
server_sock = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
server_sock.bind((self.server_host, self.server_port))
server_sock.listen(self.server_backlog)
except OSError as e:
print ('Unable to open socket: ', e)
if server_sock:
server_sock.close()
sys.exit(1)
# Wait for client connection
while True:
# Client has connected
[client_conn, client_addr] = server_sock.accept()
print ('Client has connected with address: ', client_addr)
# Create thread to serve client
thread = threading.Thread(
target = self.serve_content,
args = (client_conn, client_addr))
thread.daemon = True
thread.start()
server_sock.close()
def serve_content(self, client_conn, client_addr):
a=['a','b','c','d','e','f','g','h','i']
print ('Serving content to client with address', client_addr)
# Receive data from client
bin_data = client_conn.recv(1024)
# Echo back received data to client
for i in a:
bin_data=i
client_conn.sendall(bin_data.encode())
print(i)
time.sleep(1)
# Close connection to client
client_conn.close()
def main():
# Echo server socket parameters
server_host = 'localhost'
server_port = 50008
# Parse command line parameters if any
if len(sys.argv) > 1:
server_host = sys.argv[1]
server_port = int(sys.argv[2])
# Create EchoServer object
server = EchoServer(server_host, server_port)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("Shutting down")
except Exception:
print("Other exception")
import socket
import sys
import time
class EchoClient():
def __init__(self, server_host, server_port):
self.start(server_host, server_port)
def start(self, server_host, server_port):
# Try to connect to echo server
try:
server_sock = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
server_sock.connect((server_host, server_port))
except OSError as e:
print ('Unable to connect to socket: ', e)
if server_sock:
server_sock.close()
sys.exit(1)
# Send message string to server over socket
str_msg = input("Please enter the words you want to search Like(a?t):")
bin_msg = str_msg.encode('utf-8')
server_sock.sendall(bin_msg)
# Get response data from server and print it
while(server_sock.recv(1024)):
bin_resp = server_sock.recv(1024)
str_resp = bin_resp.decode('utf-8')
print ('Client received', str_resp)
# Close server socket
server_sock.close()
def main():
# Echo server socket parameters
server_host = 'localhost'
server_port = 50008
# Parse command line parameters if any
if len(sys.argv) > 1:
server_host = sys.argv[1]
server_port = int(sys.argv[2])
# Create EchoClient object
client = EchoClient(server_host, server_port)
if __name__ == '__main__':
main()
这是源了 |