2013-11-25 21 views
-1

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

这里是我的代码...

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 

请帮助我.. 在此先感谢..

+0

你看过'FileStream'类吗? –

+0

使用'StreamReader'和'StreamWriter'将字节转换为文本,反之亦然,'FileStream'将其保存到文件 – 2013-11-25 12:53:40

+1

[在C#.NET 3.5中保存字节\ [\]的文件](http:/ /stackoverflow.com/questions/733832/save-file-from-a-byte-in-c-sharp-net-3-5) – CodeCaster

回答

0

您可以创建一个FileStream使用File.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没有测试代码,它应该只是一个例子。

相关问题