如何让我的lua tcp服务器接收来自c# tcp客户端的消息?

本文关键字:tcp 客户端 消息 我的 lua 服务器 | 更新日期: 2023-09-27 18:11:26

所以我正在通过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

,这里是TCP客户端的c#代码:

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);
        }
    }
}
我真的希望你们能帮我解决这个问题。提前感谢,西蒙。

如何让我的lua tcp服务器接收来自c# tcp客户端的消息?

根据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中,在表中收集连续的行,并在收到整个消息时中断内部while。