Domanda

Vorrei scrivere un programma per ricevere alcuni dati usando tcpClient da un IP specificato e un numero di porta. La prima volta che l'ho fatto usando while (true). Un mio amico mi ha detto di usare thread invece di while loop. Così ho fatto come ha detto.

public static void receiveThread()
{
    TcpClient tcpClient = new TcpClient();
    try
    {
        tcpClient.Connect(ipAddress, incPort);
        Console.WriteLine("Connection accepted ...");
    }
    catch (Exception e)
    {
        Console.WriteLine(e + "\nPress enter to exit...");
        Console.ReadKey();
        return;
    }
    NetworkStream stream = tcpClient.GetStream();
    StreamReader incStreamReader = new StreamReader(stream);

    try
    {
        data = incStreamReader.ReadLine();
        Console.WriteLine("Received data: {0}", data);
    }
    catch (Exception e)
    {
        Console.WriteLine(e + "\nPress enter to exit...");
    }
}

Funziona bene ma non è buono come vorrei che funzionasse. Quando eseguo il mio programma e lo invio ad esempio "Ciao mondo" stringa, lo riceve e quindi termina il lavoro ed esce. Voglio tenere aggiornato il thread per ulteriori dati in arrivo, ma non so come farlo. Forse qualcuno ha la minima idea di come farlo?

Per inviare dati Im usando questo

using System;
using System.Net;
using System.Net.Sockets;
using System.IO;

public class Program
{
public static string ipAddress = "127.0.0.1";
public static int listenerPort = 6600;
public static string message;

static void Main(string[] args)
{
    TcpListener tcpListener = new TcpListener(IPAddress.Parse(ipAddress),listenerPort);
    tcpListener.Start();

    Socket socket = tcpListener.AcceptSocket();
    Console.WriteLine("Connection accepted...");
    while (true)
    {
        if (socket.Connected)
        {
            NetworkStream networkStream = new NetworkStream(socket);
            StreamWriter streamWriter = new StreamWriter(networkStream);

            message = Console.ReadLine();
            streamWriter.WriteLine(message);
            streamWriter.Flush();
        }
    }
}
È stato utile?

Soluzione

Dai un'occhiata a questa proprietà dell'oggetto TCPClient

http://msdn.microsoft .com / it-it / library / system.net.sockets.tcpclient.connected.aspx

puoi usarlo come tale

while(tcpClient.Connected)
{
    // do something while conn is open
}

Altri suggerimenti

Il tuo amico ti ha fatto usare un thread in modo che l'applicazione principale non fosse bloccata. Ora che hai creato un nuovo thread puoi usare un ciclo while all'interno di quel thread come facevi prima.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top