salve a tutti
ho del codice, in basso, che mi serve per ascoltare i dati che arrivano su TCP in una determinata porta (la 3001), il problema è che non riesco a mantenere la connessione aperta,se da un client mando una stringa alla porta (tutto bene), se di disconnette , poi si riconnette e ne manda un'altra , non la cattura!!!!
Nel codice si nota been che ho cercato di impostare un ciclo infinito con while(true), ma sebbene questo dopo la disconnessione del client, dopo non mi cattura i dati in entrata!!
cosa sbaglio?
codice:
using System.Net.Sockets;
class Program
{
private static BackgroundWorker worker = new BackgroundWorker();
static void Main(string[] args)
{
Program P = new Program();
P.notifyIcon1.Visible = true;
P.ipaddress = IPAddress.Any;
P.tcpServer = new TcpServer(P.ipaddress.ToString(), 3001);
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
//worker.ProgressChanged += worker_ProgressChanged;
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
if (!worker.IsBusy) worker.RunWorkerAsync();
Console.WriteLine("Press ENTER to exit the server.");
Console.ReadLine();
}
static void worker_DoWork(object sender, DoWorkEventArgs e)
{
IPEndPoint endPoint;
Socket tcpClient;
Socket listener;
int pendingConnectionQueueSize;
IPAddress ipaddress = IPAddress.Any;
endPoint = new IPEndPoint(ipaddress, 3001);
pendingConnectionQueueSize = 100;
listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(endPoint);
listener.Listen(pendingConnectionQueueSize);
Console.WriteLine("conn..");
byte[] receiveBuffer = new byte[4096];
tcpClient = listener.Accept();
tcpClient.RemoteEndPoint.ToString();
//while(true)
//{
while ((rc = tcpClient.Receive(receiveBuffer)) > 0)
{
string msg = Encoding.ASCII.GetString(receiveBuffer);
Console.WriteLine(msg.Trim());
}
//}
listener.Shutdown(SocketShutdown.Both);
listener.Close();
}
static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (!worker.IsBusy) worker.RunWorkerAsync();//restart
}
}