繁体   English   中英

如何使我的lua tcp服务器从ac#tcp客户端接收消息?

[英]How can I make my lua tcp server receive messages from a c# tcp 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);
        }
    }

}

我真的希望你们能帮助我。 预先感谢,西蒙

根据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的呼叫client:receive立即超时并失败。 将您的超时更改为正数(例如5),您的代码即可正常工作。

请注意,如果要从客户端接收多行,则可能要嵌套对client:receive的调用client:receive while 1 do client:receive ,将连续的行收集在表中,并在您启动时从内部中断已收到整个邮件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM