简体   繁体   中英

Ruby: Establish client connection on particular URI path with ruby TCPSocket

With Ruby TCPSocket I can do something like this:

@socket = TCPSocket.new "174.129.224.73", 80

which corresponds to test echo websocket ws://echo.websocket.org

But what if I need to establish connection with the socket based on

domain:10440/api/websockets

How do I do this with TCPSocket?

To put a bit more context to Steffen Ullrich's answer:

This can't be done in the way you imagine (or ask) it to be done.

The part of the URL you are asking about ( /the/path ) - known as the URI, " U nique R esource I dentifier" - is HTTP specific and isn't applicable for all TCP/IP connections.

The URI is usually requested AFTER the TCP connection is made, in accordance to the HTTP protocol (using any of the HTTP methods such as the HEAD, GET, POST etc').

The Websocket protocol uses an HTTP method called "UPGRADE" which asks the server to switch from the HTTP protocol to the Websocket protocol.

During this UPGRADE request, the resource requested is requested using it's URI. At ws://echo.websocket.org , the resource is at the root - / , but it could be anywhere and identify different websockets, such as using /echo for echo and /chat for a different web-app application.

You can see for yourself that the following line isn't connected to the websocket echo server: @socket = TCPSocket.new "174.129.224.73", 80

@socket is now connected to the HTTP server, and the websocket connection hadn't been established yet.

see what response you get for:

require 'socket'
@socket = TCPSocket.new "174.129.224.73", 80
@socket << "GET / HTTP/1.0\r\n\r\n"
@socket.read 1024
@socket.close

As you can see, you get an HTTP response.

# @socket.read(1024) # => should return "HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\nContent-Length: 61\r\n\r\n<html><head></head><body><h1>404 Not Found</h1></body></html>"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM