Sockets Can Write

I know that at least some of you saw this coming: in order for one socket to read data another socket must write data! Rejoice!

There’s really only one workhorse in terms of writing to sockets, and that’s the write method. Its usage is pretty straightforward. Just follow your intuition.

require 'socket'

Socket.tcp_server_loop(4481) do |connection|
  # Simplest way to write data to a connection.
  connection.write('Welcome!')
  connection.close
end

There’s nothing more than that to the basic write call. We’ll get to answer some more interesting questions around writing in the next chapter when we look at buffering.

System Calls From This Chapter

  • Socket#write -> write(2)