I have tried to make my first asynchronous socket program on C#, despite no error on the code, it does not accept connections. I have checked by Telnet. this is my TCP server code: I have just seen some samples on the internet but I could not find my problem, I believe that some thing else should add to my code.
class Program
{
static byte[] Mybuffer = new byte[4096];
static TcpClient tc = new TcpClient();
private static void PrintUsageInfo()
{
}
static void Main(string[] args)
{
TcpListener tl = new TcpListener(IPAddress.Parse("192.168.1.141"), 8008);
tl.Start();
tl.BeginAcceptTcpClient(OnCompleteTCP, tl);
}
static void OnCompleteReadData(IAsyncResult isa)
{
int countreadbytes = 0;
try
{
//TcpClient tc;
tc = (TcpClient)isa.AsyncState;
countreadbytes = tc.GetStream().EndRead(isa);
if (countreadbytes==0)
{
Console.WriteLine("USER Disconnected");
//client disconnect
return;
}
//continue to get data
tc.GetStream().BeginRead(Mybuffer, 0, Mybuffer.Length, OnCompleteReadData, tc);
Console.Write(Encoding.ASCII.GetString(Mybuffer));
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
static void OnCompleteTCP(IAsyncResult isa)
{
TcpListener tcpl = (TcpListener)isa.AsyncState;
tc=tcpl.EndAcceptTcpClient(isa);
tc.GetStream().BeginRead(Mybuffer, 0, Mybuffer.Length, OnCompleteReadData, tc);
}
}
So what is the problem?
Thanks to Caius Jard i have checked the netstat -a to see all listening ports and my port was not there. So I found out that this might be a problem on running process. I put the BeginAcceptTcpclient on a while(true) loop and it is working well now!
static void Main(string[] args)
{
TcpListener tl = new TcpListener(IPAddress.Any, 8008);
tl.Start();
while (true) { tl.BeginAcceptTcpClient(OnCompleteTCP, tl); }
}
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.