如何在C#中将Socket数据写入文本文件

时间:2013-11-25 12:50:11

标签: c# sockets text-files

我有一个代码片段,它从ip地址和端口读取数据。现在根据我的需要,我必须将这些数据保存到文本文件中,但我不知道该怎么做..

这是我的代码......

class Listener
{

    private TcpListener tcpListener;
    private Thread listenThread;
    // Set the TcpListener on port 8081.
    Int32 port = 8081;
    IPAddress localAddr = IPAddress.Parse("192.168.1.3");
    Byte[] bytes = new Byte[256];


    private void ListenForClients()
    {

        this.tcpListener.Start();

        while (true)
        {
            //blocks until a client has connected to the server
            TcpClient client = this.tcpListener.AcceptTcpClient();

            //create a thread to handle communication 
            //with connected client
            Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
            clientThread.Start(client);
        }
    }
    private void HandleClientComm(object client)
    {
        TcpClient tcpClient = (TcpClient)client;
        NetworkStream clientStream = tcpClient.GetStream();

        byte[] message = new byte[4096];
        int bytesRead;

        while (true)
        {
            bytesRead = 0;

            try
            {
                //blocks until a client sends a message
                bytesRead = clientStream.Read(message, 0, 4096);
            }
            catch
            {
                //a socket error has occured
                // System.Windows.MessageBox.Show("socket");
                break;
            }

            if (bytesRead == 0)
            {
                //the client has disconnected from the server
                // System.Windows.MessageBox.Show("disc");
                break;
            }

            //message has successfully been received
            ASCIIEncoding encoder = new ASCIIEncoding();

            //Here i need to save the data into text file ...

        }

        tcpClient.Close();
    }
}

我的文本文件地址是......

D:\ipdata.txt

请帮帮我.. 提前谢谢..

1 个答案:

答案 0 :(得分:0)

您可以使用FileStreamFile.Open()

创建File.OpenWrite()
using (Stream output = File.OpenWrite(@"D:\ipdata.txt"))
{
    // the while loop goes in here
}

您暗示使用ASCIIEncoding。通常,如果您收到ASCII,则无需解码数据 - 您只需将数据直接写入文件:

if (bytesRead == 0)
{
    break;
}
else
{
    output.Write(message, 0, bytesRead);
}

如果需要进行某种解码,您可能需要缓冲传入的数据,并在套接字断开后写入整个内容,或者批量写入。例如,如果您期望UTF-16,则无法保证每个Read()都会收到偶数个字节。

PS没有测试任何代码,它应该只是一个例子。