JS/HTML5 WebSocket: Connect without HTTP call

2019-02-16 11:59发布

问题:

Alright so I just tried out the new WebSocket class in HTML 5, and was pretty excited they exist; however, I fail to see how they are much more rewarding than AJAX seeing as how they still initiate an HTTP call and are not like conventional sockets. That's why I'm asking here.

Is there a way with HTML 5's WebSocket class to connect to a listening socket without sending HTTP data? Currently with TCP/IP builder it's showing all this header crap that I don't want (since I want to connect to POP3/IMAP servers without things like Flash bridges or Comet).

Possible?

Output from connection:

Listening for connections...Connected
GET / HTTP/1.1
Upgrade: WebSocket
Connection: Upgrade
Host: localhost:666
Origin: null
Sec-WebSocket-Key1: 2 987_390VNw60yi9
Sec-WebSocket-Key2: ~196  Y p  5    P67 428  ?

回答1:

No. Once the connection is established you have a true socket. But you're right that it requires special server support. So it won't let you connect to an unmodified POP or IMAP server.

They chose that design (the Upgrade mechanism) so you could easily have a server that listened for WebSocket connections as well as true HTTP requests.

There is still a big distinction from AJAX and COMET. You can use WebSockets to have true full-duplex communication between server and client. Previous browser APIs haven't provided that, forcing people to use various work-arounds (such as repeated AJAX requests, COMET's forever frame, and others).