zoukankan      html  css  js  c++  java
  • Lua 服务器Socket通信实例(转)

    local socket = require"socket"

    local host = "127.0.0.1"
    local port = "843"
    local sever = assert(socket.bind(host, port)) --绑定
    sever:settimeout(nil)   --不设置阻塞
    local tab = {}
    table.insert(tab, sever)

    while 1 do
      local s
      s,_,_ = socket.select(tab, nil, nil)
      for k, v in ipairs(s) do
        if v == sever then
        local conn  = v:accept()  --连接
        table.insert(tab, conn)
     else
       c, e = v:receive() --接收
       if c == nil then
      table.remove(tab, k)
      v:close()
        else
      if e ~= "closed" then
        print(c)
        v:send("ok ") --发送
      else
        break
      end
       end
     end
      end
    end

    --ack="ack "

    --[[while 1 do
      local conn = sever:accept()
      if conn then
     print("accep")
      end
    end--]]

    服务器的几个主要动作如下: 
         1.创建监听套接字,绑定,监听; 
         2.创建工作者线程; 
         3.创建一个套接字数组,用来存放当前所有活动的客户端套接字,每accept一个连接就更新一次数组; 
         4.接受客户端的连接。

    http://blog.csdn.net/chunleixiahe/article/details/41682891

  • 相关阅读:
    2.4 将类内联化
    2.3 提炼类
    2.2 搬移字段
    2.1 搬移函数
    1.8 替换你的算法
    1.7 以函数对象取代函数
    1.7 移除对参数的赋值动作
    1.6 分解临时变量
    1.5 引入解释性变量
    1.4 以查询取代临时变量
  • 原文地址:https://www.cnblogs.com/softidea/p/5255411.html
Copyright © 2011-2022 走看看