Question

I'm having server-clients applications. The server and clients can send and receive files using TCP and stream. The file transfer is handled in a listener which has it's own thread in my class like this:

static void Main(string[] args)
{
    Thread thread = new Thread(new ThreadStart(Listen));
    thread.Start();
}

And the Listen method (simplified):

private static void Listen()
{
    using (TcpClient tcpClient = tcpListener.AcceptTcpClient())
    {
        using (FileStream stream = new FileStream("fullFilePath.ext", FileMode.Create, FileAccess.ReadWrite))
        {
            // writing stream here
        }
    }
}

I send the file stream using (simplified):

public void SendFile(string destination, int transferPort)
{
    using (TcpClient tcpClient = new TcpClient(destination, transferPort))
    {
        using (NetworkStream networkStream = tcpClient.GetStream())
        {
            // read bytes, write, and flush here
        }
    }
}

It works fine, but I cannot figure out how to pass arguments so that Listen() can have 'dynamic' arguments I can pass to it. For example, "fullFilePath.ext" would need to be dynamic.

Any help would be appreciated.

Thanks!

Was it helpful?

Solution

I think I understand what you are trying to accomplish and unfortunately it is not possible in the way that you're describing. When doing communication across a network connection, data is sent in bytes which need to be put back together on the other side. Using serialization, you can send actual objects across the stream which can be put back together on the other end.

If you are primarily sending text files across the network and you want to preserve the file name, you might consider defining a simple class:

public class TransportFileInfo() {
    string FileName { get; set; }
    string FileContents { get; set; }
}

In your listener thread, you would receive the bytes corresponding to a serialized TransportFileInfo and then deserialize that back to it's object form. At that point you would have access to FileName and FileContents to direct your output stream appropriately.

If you do some googling for C# binary serialization I'm sure you will find information that will be useful to you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top