如何让lua tcp服务器从c#tcp客户端接收消息?

时间:2014-07-05 00:01:18

标签: c# sockets tcp lua client

所以我正在通过tcp服务器进行c#和lua之间的通信,似乎客户端连接到服务器但服务器没有收到消息。

这里是lua中服务器的代码:

-- load namespace
local socket = require("socket")
-- create a TCP socket and bind it to the local host, at any port
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 connect to localhost on port " .. port)
print (ip)
-- loop forever waiting for clients
while 1 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(0)
  -- receive the line
  local line, err = client:receive()
  print (line)
  -- 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

这里是c#中的tcp客户端代码:

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;


public class clnt
{

    public static void Main()
    {

        try
        {
            TcpClient tcpclnt = new TcpClient();
            Console.WriteLine("Connecting.....");

            tcpclnt.Connect("localhost", 2296);
            // use the ipaddress as in the server program

            Console.WriteLine("Connected");
            Console.Write("Enter the string to be transmitted : ");

            String str = Console.ReadLine();
            Stream stm = tcpclnt.GetStream();

            ASCIIEncoding asen = new ASCIIEncoding();
            byte[] ba = asen.GetBytes(str);
            Console.WriteLine("Transmitting.....");

            stm.Write(ba, 0, ba.Length);

            byte[] bb = new byte[100];
            int k = stm.Read(bb, 0, 100);

            for (int i = 0; i < k; i++)
                Console.Write(Convert.ToChar(bb[i]));

            tcpclnt.Close();
        }

        catch (Exception e)
        {
            Console.WriteLine("Error..... " + e.StackTrace);
        }
    }

}

我真的希望你们可以帮助我。 提前致谢, 西蒙

1 个答案:

答案 0 :(得分:0)

根据LuaSocket的文档:

When a timeout is set and the specified amount of time has elapsed, the affected 
methods give up and fail with an error code.

因此,对client:receive的调用会立即超时并失败。将你的超时更改为正值(比如说5),你的代码就可以了。

请注意,如果您希望从客户端接收多行,您可能还希望将调用嵌套到client:receive中的while 1 do,收集表中的连续行,以及中断当你收到整个信息的时候,就会走出内心。