How to TCPServer receive data from http request in Ruby?
Asked Answered
S

1

5

It's handy to send server response to the client by

server = TCPServer.open 1234

socket = server.accept

socket.puts 'data from server side'

and in the client side, curl in this case

curl -v localhost:1234

*   Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 1234 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.21.4 (universal-apple-darwin11.0) libcurl/7.21.4 OpenSSL/0.9.8r zlib/1.2.5
> Host: localhost:1234
> Accept: */*
> 
data from server side

at this point, it seems I can still input something in the curl, so I assume the tcp connection is bidirectional, I input

data from the curl client 

after that, how can I receive this message from curl client in the current TCPSocket instance?

I've tried

socket.read

but it doesn't work

Sophiesophism answered 17/4, 2012 at 14:20 Comment(0)
C
7

Something like this would read a greeting to a user, then wait for user input. This example simply echoes the input back on the server side.

server = TCPServer.open(8000)
socket = server.accept
socket.puts 'Hello!' # Prints Hello! to the client
while line = socket.gets
  puts line # Prints whatever the client enters on the server's output
end
Culex answered 17/4, 2012 at 14:31 Comment(4)
GET / HTTP/1.1 User-Agent: curl/7.21.4 (universal-apple-darwin11.0) libcurl/7.21.4 OpenSSL/0.9.8r zlib/1.2.5 Host: localhost:1234 Accept: /Sophiesophism
Above is the output I got, there is no client input messageSophiesophism
I was using telnet localhost 8000. I'm not sure curl supports two-way communication (yes, the shell looks like you can type something in, but that's not being sent to the server as far as I know).Culex
Thanks Dylan it seems curl only can make http request, incapable of holding a tcp socketSophiesophism

© 2022 - 2024 — McMap. All rights reserved.