so I am working on communication between c# and lua through a tcp server and it seems that the client connects to the server but the server doesn't receive a message.
Here the code of the server in 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
and here the code for the tcp client in 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);
}
}
}
I really hope you guys can help me with this. Thanks in advance, Simon
According to the documentation for 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.
So the call to client:receive
is instantly timing out and failing. Change your timeout to something positive (say 5) and your code works.
Note that if you want to receive multiple lines from a client, you will probably want to nest your call to client:receive
in while 1 do
as well, collect the successive lines in a table, and the break out of the inner while when you've received the entire message.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.