gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 02:43:39 24 4
gpt4 key购买 nike

所以我正在通过 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 的调用立即超时并失败。将您的超时设置为正数(比如 5),您的代码就可以工作了。

请注意,如果您想从客户端接收多行,您可能希望将对 client:receive 的调用嵌套在 而 1 do 中,收集表格中的连续行,以及当您收到整个消息时从内部跳出的部分。

关于c# - 如何让我的 lua tcp 服务器接收来自 c# tcp 客户端的消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24581816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com