Python Client Unable to send data to Ruby Server

I have some very simple python and ruby code that is meant to allow me to send packets from some python code to the ruby code. I was able to get this working earlier, but am now unable to recreate it. The client (python code) is able to connect to the server but never gets beyond the gets call which will block forever. Am I not sending data properly from the python side?

Ruby Code (Server):

require 'socket'
server = TCPServer.open('127.0.0.1', 8211)

# listen for commands to the server
loop {
  serverClient = server.accept
  # i am able to connect
  data_string = serverClient.gets
  # i never reach this point
  print("process data!\n")
}

Python Code (Client):

import socket
import json 

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect('127.0.0.1', 8211)

#try to send over a basic dict/json object
obj = {"Key":"Value"}
data = bytes(json.dumps(obj), "utf-8")
socket.send(data) 

1 answer

  • answered 2021-07-27 21:44 Kelsey Hannan

    Reading the ruby TCPServer docs, and this answer, it looks you need to close the client. Try this code, which can also serve multiple clients:

    require 'json'
    require 'socket'
    server = TCPServer.open('127.0.0.1', 8211)
    
    # listen for commands to the server
    loop {
      Thread.start(server.accept) do |client|
        response = client.gets
        data = JSON.parse(response)
        print("process data!\n")
        puts data
    
        client.close
      end
    }
    

    FYI: camelCase naming for variables is discouraged in ruby, use snake_case instead.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum