From 5fa3040a85cdb16af51749e5def13069c8e3be71 Mon Sep 17 00:00:00 2001 From: Cloud Wu Date: Fri, 14 Mar 2014 11:14:03 +0800 Subject: [PATCH] more example for echo socket service --- service/testsocket.lua | 41 ++++++++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/service/testsocket.lua b/service/testsocket.lua index 26ce71e7..3794fefb 100644 --- a/service/testsocket.lua +++ b/service/testsocket.lua @@ -3,27 +3,31 @@ local socket = require "socket" local mode , id = ... +local function echo(id) + socket.start(id) + + while true do + local str = socket.readline(id,"\n") + if str then + socket.write(id, str .. "\n") + else + socket.close(id) + return + end + end +end + if mode == "agent" then id = tonumber(id) skynet.start(function() - socket.start(id) - - while true do - local str = socket.readline(id,"\n") - if str then - socket.write(id, str .. "\n") - else - socket.close(id) - print("closed " .. id) - break - end - end - - skynet.exit() + skynet.fork(function() + echo(id) + skynet.exit() + end) end) else - local function accepter(id) + local function accept(id) socket.start(id) socket.write(id, "Hello Skynet\n") skynet.newservice("testsocket", "agent", id) @@ -37,8 +41,11 @@ else socket.start(id , function(id, addr) print("connect from " .. addr .. " " .. id) - -- you can also call skynet.newservice for this socket id - skynet.fork(accepter, id) + -- you have choices : + -- 1. skynet.newservice("testsocket", "agent", id) + -- 2. skynet.fork(echo, id) + -- 3. accept(id) + accept(id) end) end) end \ No newline at end of file