-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
请帮助我.. 在此先感谢..
你看过'FileStream'类吗? –
使用'StreamReader'和'StreamWriter'将字节转换为文本,反之亦然,'FileStream'将其保存到文件 – 2013-11-25 12:53:40
[在C#.NET 3.5中保存字节\ [\]的文件](http:/ /stackoverflow.com/questions/733832/save-file-from-a-byte-in-c-sharp-net-3-5) – CodeCaster