You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
1.8 KiB
68 lines
1.8 KiB
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Server
|
|
{
|
|
class Server
|
|
{
|
|
private readonly int BUFF_SIZE = 1024;
|
|
|
|
private TcpListener listener;
|
|
|
|
public async void Start()
|
|
{
|
|
listener = new TcpListener(IPAddress.Any, 7000);
|
|
listener.Start();
|
|
|
|
while (true)
|
|
{
|
|
TcpClient client = await listener.AcceptTcpClientAsync().ConfigureAwait(false);
|
|
string clientEndPoint = client.Client.RemoteEndPoint.ToString();
|
|
NetworkStream stream = client.GetStream();
|
|
|
|
// Receive data size
|
|
byte[] bytes = new byte[4];
|
|
int readSize = await stream.ReadAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
|
|
if (readSize != 4)
|
|
throw new ApplicationException("Invalid size");
|
|
|
|
int totalSize = BitConverter.ToInt32(bytes, 0);
|
|
Console.WriteLine($"[{clientEndPoint}] Data size: {totalSize} byte");
|
|
|
|
// Receive data
|
|
string fileName = Guid.NewGuid().ToString("N") + ".png";
|
|
using (FileStream fs = new FileStream(fileName, FileMode.CreateNew))
|
|
{
|
|
byte[] buff = new byte[BUFF_SIZE];
|
|
int received = 0;
|
|
while (received < totalSize)
|
|
{
|
|
int size = totalSize - received >= BUFF_SIZE ? BUFF_SIZE : totalSize - received;
|
|
readSize = await stream.ReadAsync(buff, 0, size).ConfigureAwait(false);
|
|
received += readSize;
|
|
|
|
await fs.WriteAsync(buff, 0, readSize);
|
|
|
|
Console.WriteLine($"[{clientEndPoint}] Receive: {received}/{totalSize}");
|
|
}
|
|
}
|
|
|
|
// Send result
|
|
byte[] result = new byte[1];
|
|
result[0] = 1;
|
|
await stream.WriteAsync(result, 0, result.Length).ConfigureAwait(false);
|
|
|
|
Console.WriteLine($"[{clientEndPoint}] Result: {(result[0] == 1 ? "success" : "fail")}");
|
|
|
|
stream.Close();
|
|
client.Close();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|