我正在编写一个tcp监听器来将每个连接保存到文件
代码如下:
using NDesk.Options;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Command.Socket
{
public class Socket
{
public Socket()
{
Port = 4380;
}
int Port { get; set; }
public async void RunServerAsync()
{
var listener = new TcpListener(IPAddress.Any, Port);
listener.Start();
try
{
while (true)
{
Accept(await listener.AcceptTcpClientAsync());
//Console.WriteLine("ha!");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
listener.Stop();
}
Console.WriteLine("");
}
private async Task Accept(TcpClient client)
{
await Task.Yield();
try
{
using (client)
using (NetworkStream n = client.GetStream())
using (StreamWriter file = new StreamWriter(DateTime.Now.ToFileTimeUtc() + "text"))
{
byte[] data = new byte[500];
int bytesRead = 0;
int chunkSize = 1;
while (bytesRead < data.Length && chunkSize > 0)
{
bytesRead += chunkSize = await n.ReadAsync(data, bytesRead, data.Length - bytesRead);
Array.Reverse(data);
string[] sata = data.Select(d => d.ToString()).ToArray();
foreach (var s in sata)
{
file.Write(s);
}
file.Write(Environment.NewLine);
await n.WriteAsync(data, 0, data.Length);
}
}
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
}
}
}
我使用Socket类如下:
Socket socket = new Socket();
socket.RunServerAsync();
我的问题是代码离开while循环没有任何错误或消息。 如果你想测试它,只需创建一个控制台应用程序并创建一个类并使用它。