Initial Server and Client for recommond engine
This commit is contained in:
48
recommondation-engine/client.js
Normal file
48
recommondation-engine/client.js
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
const net = require("net");
|
||||||
|
|
||||||
|
// Function to get recommendations from the Python server
|
||||||
|
function getRecommendations(userId) {
|
||||||
|
const client = new net.Socket();
|
||||||
|
|
||||||
|
// Connect to the server on localhost at port 9999
|
||||||
|
client.connect(9999, "localhost", function () {
|
||||||
|
console.log(`Connected to server, sending user_id: ${userId}`);
|
||||||
|
|
||||||
|
// Send the user_id in JSON format
|
||||||
|
const message = JSON.stringify({ user_id: userId });
|
||||||
|
client.write(message);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Listen for data from the server
|
||||||
|
client.on("data", function (data) {
|
||||||
|
const recommendations = JSON.parse(data.toString());
|
||||||
|
console.log(
|
||||||
|
`Recommendations for User ${userId}:`,
|
||||||
|
recommendations.recommendations,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Close the connection after receiving the response
|
||||||
|
client.destroy();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Handle connection errors
|
||||||
|
client.on("error", function (error) {
|
||||||
|
console.error("Connection error:", error.message);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Handle connection close
|
||||||
|
client.on("close", function () {
|
||||||
|
console.log(`Connection to server closed for User ${userId}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function to simulate multiple users requesting recommendations
|
||||||
|
function simulateClients() {
|
||||||
|
for (let i = 1; i <= 5; i++) {
|
||||||
|
setTimeout(() => {
|
||||||
|
getRecommendations(i); // Simulate clients with IDs 1 to 5
|
||||||
|
}, i * 1000); // Stagger requests every second
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
simulateClients();
|
||||||
@@ -1,24 +1,42 @@
|
|||||||
import asyncio
|
import socket
|
||||||
import websockets
|
import threading
|
||||||
|
import json
|
||||||
|
|
||||||
async def handle_client(websocket, path):
|
# Sample recommendations function
|
||||||
try:
|
def get_recommendations(user_id):
|
||||||
# Receive user ID
|
# This is a mock function. Replace it with your actual recommendation logic.
|
||||||
user_id = await websocket.recv()
|
return {"recommendations": [f"Product {user_id} - Item 1", f"Product {user_id} - Item 2", f"Product {user_id} - Item 3"]}
|
||||||
print(f"Received user ID: {user_id}")
|
|
||||||
|
|
||||||
# Optional: You can add more logic here if needed
|
# Handle client connection
|
||||||
|
def handle_client(client_socket, client_address):
|
||||||
|
print(f"New connection from {client_address}")
|
||||||
|
|
||||||
except websockets.exceptions.ConnectionClosed:
|
# Receive the client request (user_id)
|
||||||
print("Client disconnected")
|
request = client_socket.recv(1024).decode("utf-8")
|
||||||
except Exception as e:
|
if request:
|
||||||
print(f"Error processing request: {str(e)}")
|
data = json.loads(request)
|
||||||
|
user_id = data.get("user_id")
|
||||||
|
|
||||||
async def start_server():
|
# Get recommendations for the user
|
||||||
server = await websockets.serve(handle_client, "localhost", 5555)
|
recommendations = get_recommendations(user_id)
|
||||||
print("WebSocket server started")
|
|
||||||
await server.wait_closed()
|
# Send the response back to the client
|
||||||
|
client_socket.send(json.dumps(recommendations).encode("utf-8"))
|
||||||
|
|
||||||
|
# Close the connection after sending the response
|
||||||
|
client_socket.close()
|
||||||
|
|
||||||
|
# Start the server to handle multiple clients
|
||||||
|
def start_server():
|
||||||
|
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
server.bind(("0.0.0.0", 9999)) # Bind to all interfaces on port 9999
|
||||||
|
server.listen(5)
|
||||||
|
print("Server listening on port 9999...")
|
||||||
|
|
||||||
|
while True:
|
||||||
|
client_socket, client_address = server.accept()
|
||||||
|
client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
|
||||||
|
client_thread.start()
|
||||||
|
|
||||||
# Run the server
|
# Run the server
|
||||||
if __name__ == "__main__":
|
start_server()
|
||||||
asyncio.run(start_server())
|
|
||||||
|
|||||||
Reference in New Issue
Block a user