我想通过TCP将数据发送到特定的IP地址\端口。我已经编写了一个示例,应该向那里发送一些字符串:
internal class TcpSender : BaseDataSender
{
public TcpSender(Settings settings) : base(settings)
{
}
public async override Task SendDataAsync(string data)
{
Guard.ArgumentNotNullOrEmptyString(data, nameof(data));
byte[] sendData = Encoding.UTF8.GetBytes(data);
using (var client = new TcpClient(Settings.IpAddress, Settings.Port))
using (var stream = client.GetStream())
{
await stream.WriteAsync(sendData, 0, sendData.Length);
}
}
}
这里的问题是我的流在tcp客户端发送所有数据之前被处理掉了。我应该如何重写代码,等待所有数据被写入,然后再释放所有资源?谢谢。
更新:从控制台实用程序调用。
static void Main(string[] args)
{
// here settings and date are gotten from args
try
{
GenerateAndSendData(settings, date)
.GetAwaiter()
.GetResult();
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e);
}
}
public static async Task GenerateAndSendData(Settings settings, DateTime date)
{
var sender = new TcpSender(settings);
await sender.SendDataAsync("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.");
}
更新2:回声服务器代码(从某个stackoverflow问题中盗用):
class TcpEchoServer
{
static TcpListener listen;
static Thread serverthread;
public static void Start()
{
listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 514);
serverthread = new Thread(new ThreadStart(DoListen));
serverthread.Start();
}
private static void DoListen()
{
// Listen
listen.Start();
Console.WriteLine("Server: Started server");
while (true)
{
Console.WriteLine("Server: Waiting...");
TcpClient client = listen.AcceptTcpClient();
Console.WriteLine("Server: Waited");
// New thread with client
Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));
clientThread.Start(client);
}
}
private static void DoClient(object client)
{
// Read data
TcpClient tClient = (TcpClient)client;
Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId);
do
{
if (!tClient.Connected)
{
tClient.Close();
Thread.CurrentThread.Abort(); // Kill thread.
}
if (tClient.Available > 0)
{
byte pByte = (byte)tClient.GetStream().ReadByte();
Console.WriteLine("Client (Thread: {0}): Data {1}", Thread.CurrentThread.ManagedThreadId, pByte);
tClient.GetStream().WriteByte(pByte);
}
// Pause
Thread.Sleep(100);
} while (true);
}
}
.Flush
。 - Daniel A. Whitesocket.Shutdown
来刷新它。但看起来你应该使用TCPClient
的Close
方法。 - Jeroen van Langen