Home
Ratchet Library :: TCP Sockets Example
API  ·  Manual

Hello World: TCP Sockets

require "ratchet"

function ctx1(where)
    local rec = ratchet.socket.prepare_uri(where)
    local socket = ratchet.socket.new(rec.family, rec.socktype, rec.protocol)
    socket:setsockopt("SO_REUSEADDR", true)
    socket:bind(rec.addr)
    socket:listen()

    ratchet.thread.attach(ctx2, "tcp://localhost:10025")

    local client = socket:accept()

    -- Portion being tested.
    --
    client:send("hello")
    local data = client:recv()
    assert(data == "world")

    local data = client:recv()
    assert(data == "foo")
    client:send("bar")
end

function ctx2(where)
    local rec = ratchet.socket.prepare_uri(where)
    local socket = ratchet.socket.new(rec.family, rec.socktype, rec.protocol)
    socket:connect(rec.addr)

    -- Portion being tested.
    --
    local data = socket:recv()
    assert(data == "hello")
    socket:send("world")

    socket:send("foo")
    local data = socket:recv()
    assert(data == "bar")
end

kernel = ratchet.new(function ()
    ratchet.thread.attach(ctx1, "tcp://localhost:10025")
end)
kernel:loop()



Last modified:  Sun, 17 Aug 2014 09:32:32 -0400
Author:  icgood