Objective – To implement a HTTP server in Python which handles just one request
ID: 674935 • Letter: O
Question
Objective – To implement a HTTP server in Python which handles just one request from user. Objective – To implement a HTTP server in Python which handles just one request from user.
Design a server that serves a ‘.html’ file. When the server receives a HTTP request from your web-browser, it should send this file back to the web-browser with proper header information and browser should display that html page. You must build your header with Content-Type and ContentLength after an appropriate status code. Server port number – 8080 Create a socket listening on this port and break down the received packet. Build a proper response header format and send it back to your browser, along with requested data. Design a very simple HTML page and name it ‘DN.html’. Save it in a directory. Browser should display 404 Not found message if the requested page is other than ‘DN.html’. We will test your code by running your server script and then requesting a page from your web browser. E.g. -> 127.0.0.1:8080/DN.html on browser should display the page Submit README, your code and .html file
Notes - Usage of any modules (such as BeseHTTPserver) for HTTP server is not accepted. Follow defensive coding technique.
Explanation / Answer
To implement a HTTP server in Python which handles just one request from user.
import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), Handler)
print("serving at port", PORT)
httpd.serve_forever()
python -m http.server 8000
python -m http.server 8000 --bind 127.0.0.1 (bind arguments to specifie the address to which should to bind)
python -m http.server --cgi 8000 (contain CGI scripts)
Running this function with no arguments which test initially and after the each request. If its return value
as true, the server continues.
def run_while_true(server_class=BaseHTTPServer.HTTPServer,
handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
while keep_running():
httpd.handle_request()
First Create a http server
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World ');
}).listen(8080, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8080/');
the below code for socket connecting port
<script src="socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
</script>
Creating js file and DN.html
create a server.js:
var http = require('http'), url = require('url'), fs = require('fs'), io = require('socket.io'), server;
server = http.createServer(function(req, res){
var path = url.parse(req.url).pathname;
switch (path){
case '/DN.html':
fs.readFile(__dirname + path, function(err, data){
if (err) return send404(res);
res.writeHead(200, {'Content-Type' : 'text/html'})
res.write(data, 'utf8');
res.end();
});
break;
default: send404(res);
}
}),
send404 = function(res){
res.writeHead(404);
res.write('404');
res.end();
};
server.listen(8080);
var io = io.listen(server)
var numberOfClients = 0;
io.sockets.on('connection', function(client){
players.push(client.id);
client.on('adduser', function(username){
client.set('nick', username, function() {
client.set('nick', function(err, nick) {
io.sockets.json.send({ connectVar: [nick, client.id] });
}
});
numberOfClients = numberOfClients+1;
io.sockets.json.send({ numberOfClients: numberOfClients});
});
client.on('disconnect', function(){
client.get('nick', function (err, nick) {
io.sockets.json.send({ disconnectVar: [nick, client.id] });
});
numberOfClients = numberOfClients-1;
io.sockets.json.send({ numberOfClients: numberOfClients});
//send all the clients the updated number of clients
});
});
create a DN.html:
<html>
<head>
<meta charset="utf-8">
<title>connection with server</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
function handle(data){
if (data.connectVar) {
var userid = data.connectVar[1];
var username = data.connectVar[0];
var connectionDiv = document.getElementById('connection of Div');
connectionDiv.innerHTML = username + ' connected';
connectionDiv.style.display = 'block';
}
else if (data.disconnectVar) {
var userid = data.disconnectVar[1];
var username = data.disconnectVar[0];
var connectionDiv = document.getElementById('connection of Div');
connectionDiv.innerHTML = username + ' disconnected';
connectionDiv.style.display = 'block';
}
else if (data.numberOfPlayers) {
var numberOfPlayers = data.numberOfPlayers;
var numberDiv = document.getElementById('connectedPlayers');
numberDiv.innerHTML = 'Connected players: ' + numberOfPlayers;
}
}
var socket = io.connect('http://localhost:8080');
socket.on('connect', function(){
socket.emit('adduser', prompt("What is your desired username"));
});
socket.on('message', function(data){
handle(data);
});
</script>
<div id='connectedPlayers'>Connected players: 1</div>
<div id='connectionDiv'></div>
</body>
</html>
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.