2013-04-10 54 views
0

我想了解Socket類和我使用下面的例子來實現服務器樣本如何遠程登錄地址?

local server = assert(socket.bind("*", 0)) 

-- find out which port the OS chose for us 
local ip, port = server:getsockname() 

-- print a message informing what's up 
print("Please telnet to localhost on IP [" ..ip.. "] and port [" .. port .. "]") 
print("After connecting, you have 10s to enter a line to be echoed") 

-- loop forever waiting for clients 
while true do 
-- wait for a connection from any client 
local client = server:accept() 

-- make sure we don't block waiting for this client's line 
client:settimeout(10) 

-- receive the line 
local line, err = client:receive() 

-- if there was no error, send it back to the client 
if not err then 
    client:send(line .. "\n") 
end 

-- done with client, close the object 
client:close() 
end 

但現在的問題是,我怎麼可以telnet例如地址本地主機:通過LUA 8080 ?

編輯: 我忘了說什麼,我甚至不能在cmd上telnet。當我鍵入命令:

的telnet IP端口

它總是說「連接丟失」後,我發送消息。我究竟做錯了什麼?

回答

1

完成!

local socket = require("socket") 

local server = socket.connect(ip, port) 

local ok, err = server:send("RETURN\n") 
if (err ~= nil) then 
    print (err) 
else 
    while true do 
     s, status, partial = server:receive(1024) 
     print(s or partial) 

     if (status == "closed") then 
      break 
     end 
    end 
end 

server:close() 
2

首先,按照說明從here將啓動telnet在Windows 7:

  1. 進入控制面板
  2. 查找ProgramsTurn Windows features on or off(取決於佈局)
  3. 查找Telnet client並啓用它。

一旦你這樣做了,它應該按預期工作。

+0

我這樣做了。實際上,當我輸入telnet命令,它連接,但當我發送一條消息(例如「你好」),我的連接丟失,我的lua程序無法收到消息。我不知道爲什麼... – Crasher 2013-04-10 14:57:31

+0

Telnet需要客戶端和服務器。 – Zyerah 2013-04-10 16:02:59

+0

我的客戶端和服務器處於活動狀態,但仍然收到相同的消息,不知道爲什麼... – Crasher 2013-04-10 16:50:47