browsers close socket before the response is fully downloaded

  • Last Update :
  • Techknowledgy :

All you really need to play a video file (or more accurately stream a video file as pointed by @hrunting) as far as http headers for the response are concerned is:

HTTP / 1.0 200 OK
Server: SimpleHTTP / 0.6 Python / 3.5 .0
Date: Sat, 02 Jan 2016 02: 45: 34 GMT
Content - type: video / mp4
Content - Length: 33455269
Last - Modified: Sat, 02 Jan 2016 02: 45: 27 GMT

Here's some code based on your initial question that does what you want:

import http.server

class SuperHandler(http.server.SimpleHTTPRequestHandler):
   def do_GET(self):
   path = self.path
encodedFilePath = 'file.mp4'

with open(encodedFilePath, 'rb') as videoFile:
   self.send_response(200)
self.send_header('Content-type', 'video/mp4')
self.send_header('Content-Disposition', 'attachment; filename=' + encodedFilePath)
self.end_headers()
self.copyfile(videoFile, self.wfile)

server_address = ('', 8000)
handler_class = SuperHandler
httpd = http.server.HTTPServer(server_address, handler_class)
httpd.serve_forever()

Suggestion : 2

Occasionally, when downloading a file in a web browser, the download progress doesn't "know" the total size of the file, or how far along in the download it is -- it just shows the speed at which it's downloading, with a total as "Unknown"., 3 Possible duplicate of How does browser know how much page has been loaded?, Estimated Time Left and Total File Size not showing up in Download ... – Karan Jul 9, 2013 at 17:52 ,Why wouldn't the browser know the final size of some files? Where does it get this information in the first place?,Anyway, whatever the reason is, the header can be missing. In that case the browser doesn't know how much data the server is going to send, and thus displays the document size as unknown, waiting for the server to close the connection. And that's the reason for unknown document sizes.

First, your browser connects to the website's server and sends a URL of the document it wants to download (web pages are documents, too) and some details about the browser itself (User-Agent etc). For example, to load the main page on the SuperUser site, http://superuser.com/, my browser sends a request that looks like this:

GET / HTTP / 1.1
Host: superuser.com
Connection: keep - alive
Accept: text / html, application / xhtml + xml, application / xml;
q = 0.9, *
/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.0 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
Cookie: [removed for security]
DNT: 1
If-Modified-Since: Tue, 09 Jul 2013 07:14:17 GMT

The first line specifies which document the server should return. The other lines are called headers; they look like this:

Header name: Header value

If all is well, the server will respond by sending the requested document. The response starts off with a status message, followed by some headers (with details about the document) and finally, if all is well, the document's content. This is what the SuperUser server's reply for my request looks like:

HTTP/1.1 200 OK
Cache-Control: public, max-age=60
Content-Type: text/html; charset=utf-8
Expires: Tue, 09 Jul 2013 07:27:20 GMT
Last-Modified: Tue, 09 Jul 2013 07:26:20 GMT
Vary: *
X-Frame-Options: SAMEORIGIN
Date: Tue, 09 Jul 2013 07:26:19 GMT
Content-Length: 139672

<!DOCTYPE html>
<html>
[...snip...]

</html>

Suggestion : 3

The proxy server MUST signal persistent connections separately with its clients and the origin servers (or other proxy servers) that it connects to. Each persistent connection applies to only one transport link. , If either the client or the server sends the close token in the Connection header, that request becomes the last one for the connection. , An HTTP/1.1 server MAY assume that a HTTP/1.1 client intends to maintain a persistent connection unless a Connection header including the connection-token "close" was sent in the request. If the server chooses to close the connection immediately after sending the response, it SHOULD send a Connection header including the connection-token close. , Servers SHOULD always respond to at least one request per connection, if at all possible. Servers SHOULD NOT close a connection in the middle of transmitting a response, unless a network or client failure is suspected.

Persistent HTTP connections have a number of advantages:

      -By opening and closing fewer TCP connections, CPU time is saved
         in routers and hosts(clients, servers, proxies, gateways,
            tunnels, or caches), and memory used
      for TCP protocol control
      blocks can be saved in hosts.
      - By opening and closing fewer TCP connections, CPU time is saved
        in routers and hosts (clients, servers, proxies, gateways,
        tunnels, or caches), and memory used for TCP protocol control
        blocks can be saved in hosts.
      -HTTP requests and responses can be pipelined on a connection.
      Pipelining allows a client to make multiple requests without
      waiting
      for each response, allowing a single TCP connection to
      be used much more efficiently, with much lower elapsed time.
      - HTTP requests and responses can be pipelined on a connection.
        Pipelining allows a client to make multiple requests without
        waiting for each response, allowing a single TCP connection to
        be used much more efficiently, with much lower elapsed time.
      -Network congestion is reduced by reducing the number of packets
      caused by TCP opens, and by allowing TCP sufficient time to
      determine the congestion state of the network.
      - Latency on subsequent requests is reduced since there is no time
        spent in TCP's connection opening handshake.
      -HTTP can evolve more gracefully, since errors can be reported
      without the penalty of closing the TCP connection.Clients using
      future versions of HTTP might optimistically
      try a new feature,
      but
      if communicating with an older server, retry with old
      semantics after an error is reported.

Requirements for HTTP/1.1 clients:

      -If a client will wait
      for a 100(Continue) response before
      sending the request body, it MUST send an Expect request - header
      field(section 14.20) with the "100-continue"
      expectation.

Suggestion : 4

If you are too quick, you might start the client before the server has a chance to initialize itself and begin listening on the port. If this happens, you will see a stack trace from the client. If this happens, just restart the client.,The following section looks in detail at each class in both the client and the server and then shows you how to run them.,Again, the client echoes what you type and sends the text to the server. The server responds with the punch line. Now your screen should contain this:,The client echoes what you type and sends the text to the server. The server responds with the first line of one of the many Knock Knock jokes in its repertoire. Now your screen should contain this (the text you typed is in bold):

java KnockKnockServer 4444
int portNumber = Integer.parseInt(args[0]);

try (
   ServerSocket serverSocket = new ServerSocket(portNumber); Socket clientSocket = serverSocket.accept(); PrintWriter out =
   new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(
      new InputStreamReader(clientSocket.getInputStream()));
) {
clientSocket = serverSocket.accept();
try (
   // ...
   PrintWriter out =
   new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(
      new InputStreamReader(clientSocket.getInputStream()));
) {
   String inputLine, outputLine;

   // Initiate conversation with client
   KnockKnockProtocol kkp = new KnockKnockProtocol();
   outputLine = kkp.processInput(null);
   out.println(outputLine);

   while ((inputLine = in.readLine()) != null) {
      outputLine = kkp.processInput(inputLine);
      out.println(outputLine);
      if (outputLine.equals("Bye."))
         break;
   }
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);

try (
   Socket kkSocket = new Socket(hostName, portNumber); PrintWriter out = new PrintWriter(kkSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(
      new InputStreamReader(kkSocket.getInputStream()));
)
java KnockKnockClient knockknockserver.example.com 4444

Suggestion : 5

The WebSocket object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.,To construct a WebSocket, use the WebSocket() constructor., Fired when a connection with a WebSocket has been closed because of an error, such as when some data couldn't be sent. Also available via the onerror property. , Fired when a connection with a WebSocket is closed. Also available via the onclose property

// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');

// Connection opened
socket.addEventListener('open', (event) => {
   socket.send('Hello Server!');
});

// Listen for messages
socket.addEventListener('message', (event) => {
   console.log('Message from server ', event.data);
});

Suggestion : 6

© 2007—2022  Ilya Kantor

let socket = new WebSocket("ws://javascript.info");
let socket = new WebSocket("wss://javascript.info/article/websocket/demo/hello");

socket.onopen = function(e) {
   alert("[open] Connection established");
   alert("Sending to server");
   socket.send("My name is John");
};

socket.onmessage = function(event) {
   alert(`[message] Data received from server: ${event.data}`);
};

socket.onclose = function(event) {
   if (event.wasClean) {
      alert(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
   } else {
      // e.g. server process killed or network down
      // event.code is usually 1006 in this case
      alert('[close] Connection died');
   }
};

socket.onerror = function(error) {
   alert(`[error] ${error.message}`);
};
GET / chat
Host: javascript.info
Origin: https: //javascript.info
   Connection: Upgrade
Upgrade: websocket
Sec - WebSocket - Key: Iv8io / 9 s + lYFgZWcXczP8Q ==
   Sec - WebSocket - Version: 13
101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec - WebSocket - Accept: hsBlbuDTkk24srzEOTBUlZAlC2g =
let socket = new WebSocket("wss://javascript.info/chat", ["soap", "wamp"]);
GET / chat
Host: javascript.info
Upgrade: websocket
Connection: Upgrade
Origin: https: //javascript.info
   Sec - WebSocket - Key: Iv8io / 9 s + lYFgZWcXczP8Q ==
   Sec - WebSocket - Version: 13
Sec - WebSocket - Extensions: deflate - frame
Sec - WebSocket - Protocol: soap, wamp