This code snippet demonstrates how to transfer files from a client to a server. In this example, both the client and server are console applications and use the TcpClient/TcpListener classes. The client sends the filesize and filename to the server before sending the file. The server uses the filesize to determine how much data to expect from the client and uses the filename to save the file locally.
Client
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
namespace FileTransferClient
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Please enter a full file path");
string fileName = Console.ReadLine();
TcpClient tcpClient = new TcpClient("127.0.0.1", 1234);
Console.WriteLine("Connected. Sending file.");
StreamWriter sWriter = new StreamWriter(tcpClient.GetStream());
byte[] bytes = File.ReadAllBytes(fileName);
sWriter.WriteLine(bytes.Length.ToString());
sWriter.Flush();
sWriter.WriteLine(fileName);
sWriter.Flush();
Console.WriteLine("Sending file");
tcpClient.Client.SendFile(fileName);
}
catch (Exception e)
{
Console.Write(e.Message);
}
Console.Read();
}
}
}
Server
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
namespace FileTransfer
{
class Program
{
static void Main(string[] args)
{
// Listen on port 1234
TcpListener tcpListener = new TcpListener(IPAddress.Any, 1234);
tcpListener.Start();
Console.WriteLine("Server started");
//Infinite loop to connect to new clients
while (true)
{
// Accept a TcpClient
TcpClient tcpClient = tcpListener.AcceptTcpClient();
Console.WriteLine("Connected to client");
StreamReader reader = new StreamReader(tcpClient.GetStream());
// The first message from the client is the file size
string cmdFileSize = reader.ReadLine();
// The first message from the client is the filename
string cmdFileName = reader.ReadLine();
int length = Convert.ToInt32(cmdFileSize);
byte[] buffer = new byte[length];
int received = 0;
int read = 0;
int size = 1024;
int remaining = 0;
// Read bytes from the client using the length sent from the client
while (received < length)
{
remaining = length - received;
if (remaining < size)
{
size = remaining;
}
read = tcpClient.GetStream().Read(buffer, received, size);
received += read;
}
// Save the file using the filename sent by the client
using (FileStream fStream = new FileStream(Path.GetFileName(cmdFileName), FileMode.Create))
{
fStream.Write(buffer, 0, buffer.Length);
fStream.Flush();
fStream.Close();
}
Console.WriteLine("File received and saved in " + Environment.CurrentDirectory);
}
}
}
}
1 comment:
Братуха,на разные компьютеры не передаётся
Post a Comment