57 lines
No EOL
1.9 KiB
Python
57 lines
No EOL
1.9 KiB
Python
import socket
|
|
|
|
|
|
class RFC2229Client:
|
|
def __init__(self):
|
|
self.sock = None
|
|
|
|
def connect(self, host='dict.org', port=2628):
|
|
"""Establish a connection to the dictionary server."""
|
|
self.sock = socket.create_connection((host, port))
|
|
|
|
"""Read the response from the server."""
|
|
response = self.sock.recv(4096).decode('utf-8')
|
|
print(response)
|
|
return response
|
|
|
|
def define(self, word, database='!'):
|
|
"""Request a definition for a word and parse the multi-line response."""
|
|
self._send_command(f"DEFINE {database} {word}")
|
|
# Use a file-like interface for line-by-line reading.
|
|
file = self.sock.makefile('r', encoding='utf-8')
|
|
# Read the initial response header.
|
|
header = file.readline()
|
|
response_lines = [header.rstrip('\r\n')]
|
|
# Read subsequent lines until a single dot indicates the end.
|
|
for line in file:
|
|
line = line.rstrip('\r\n')
|
|
if line == '.':
|
|
break
|
|
response_lines.append(line)
|
|
return "\n".join(response_lines)
|
|
|
|
def match(self, word, strategy='.', database='!'):
|
|
"""Request matches for a word."""
|
|
self._send_command(f"MATCH {database} {strategy} {word}")
|
|
return self._read_response()
|
|
|
|
def quit(self):
|
|
"""Close the connection to the server."""
|
|
self._send_command("QUIT")
|
|
self.sock.close()
|
|
self.sock = None
|
|
|
|
def _send_command(self, command):
|
|
"""Send a command to the server."""
|
|
if not self.sock:
|
|
raise ConnectionError("Not connected to the server.")
|
|
self.sock.sendall(f"{command}\r\n".encode('utf-8'))
|
|
|
|
if __name__ == "__main__":
|
|
client = RFC2229Client()
|
|
try:
|
|
client.connect()
|
|
word = input("Enter a word to define: ")
|
|
print(client.define(word))
|
|
finally:
|
|
client.quit() |