.NET 3.x TCP Клиент-Сервер, передача файлов, упрощение кода - C#
Формулировка задачи:
TCP Клиент Сервер передача файлов упрощение
Вот стартовый пример передачи файлов , я нашкрябал Раклями своими
от клиента серверу
Сервер консольный
Клиент WinForm
К сожалению происходит зависание передачи
есть тоже хороший пример передачи файлов
http://www.interestprograms.ru/sourc...ov-po-seti-tcp
но если его разбирать он как клубок связан сам с собой сложно
а очень хочется простой пример передачи файлов
от клиента к серверу
и наоборот от сервера к клиенту
в примере http://www.interestprograms.ru/sourc...ov-po-seti-tcp
Используеться класс MemoryStream ?
не понятно зачем он там нужен , если достаточно просто Stream
товарищи подкинте что то, или как правильно
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
namespace ConsoleApplication_Server
{
class Program
{
private static TcpListener listner;
private const int MAXBUFFER = 1048576;
private const int LENGTHHEADER = 9;
private byte[] buffer;
private static Stream strLocal;
private MemoryStream ms;
private static NetworkStream strRemote;
private BinaryFormatter bf;
private static Thread threaddown;
// Удобный контейнер для подключенного клиента.
private TcpClient _tcpClient;
static void Main(string[] args)
{
Title_Console("Сервер Файлов v1.0");
string ip = "127.0.0.1";
Int32 port = 11000;
try
{
if (listner == null)
{
listner = new TcpListener(new IPEndPoint(IPAddress.Parse(ip), port));
listner.Start();
//поток
threaddown = new Thread(StartReceiving);
Console.WriteLine("Сервер Запущен!");
}
}
catch (Exception e)
{
listner.Stop();
listner = null;
Console.WriteLine(e.Message);
}
Console.ReadKey(true);
}
private static int PercentProgress;
private void UpdateProgress(Int64 BytesRead, Int64 TotalBytes)
{
if (TotalBytes > 0)
{
// Calculate the download progress in percentages
PercentProgress = Convert.ToInt32((BytesRead * 100) / TotalBytes);
// Make progress on the progress bar
//prgDownload.Value = PercentProgress;
Console.WriteLine("Progress: "+PercentProgress);
}
}
private static void StartReceiving()
{
// There are many lines in here that can cause an exception
try
{
// Write the status to the log textbox on the form (txtLog)
//this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "Starting the server...\r\n" });
// Start the TCP listener and listen for connections
// Write the status to the log textbox on the form (txtLog)
//this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "The server has started. Please connect the client to " + ipaLocal.ToString() + "\r\n" });
// Accept a pending connection
TcpClient tclServer = listner.AcceptTcpClient();
// Write the status to the log textbox on the form (txtLog)
//this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "The server has accepted the client\r\n" });
// Receive the stream and store it in a NetworkStream object
strRemote = tclServer.GetStream();
// Write the status to the log textbox on the form (txtLog)
//this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "The server has received the stream\r\n" });
// For holding the number of bytes we are reading at one time from the stream
int bytesSize = 0;
// The buffer that holds the data received from the client
byte[] downBuffer = new byte[2048];
// Read the first buffer (2048 bytes) from the stream - which represents the file name
bytesSize = strRemote.Read(downBuffer, 0, 2048);
// Convert the stream to string and store the file name
string FileName = System.Text.Encoding.ASCII.GetString(downBuffer, 0, bytesSize);
// Set the file stream to the path C:\ plus the name of the file that was on the sender's computer
strLocal = new FileStream(@"C:" + FileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
// The buffer that holds the data received from the client
downBuffer = new byte[2048];
// Read the next buffer (2048 bytes) from the stream - which represents the file size
bytesSize = strRemote.Read(downBuffer, 0, 2048);
// Convert the file size from bytes to string and then to long (Int64)
long FileSize = Convert.ToInt64(System.Text.Encoding.ASCII.GetString(downBuffer, 0, bytesSize));
// Write the status to the log textbox on the form (txtLog)
//this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "Receiving file " + FileName + " (" + FileSize + " bytes)\r\n" });
// The buffer size for receiving the file
downBuffer = new byte[2048];
// From now on we read everything that's in the stream's buffer because the file content has started
while ((bytesSize = strRemote.Read(downBuffer, 0, downBuffer.Length)) > 0)
{
// Write the data to the local file stream
strLocal.Write(downBuffer, 0, bytesSize);
// Update the progressbar by passing the file size and how much we downloaded so far to UpdateProgress()
//this.Invoke(new UpdateProgressCallback(this.UpdateProgress), new object[] { strLocal.Length, FileSize });
}
// When this point is reached, the file has been received and stored successfuly
}
finally
{
// This part of the method will fire no matter wether an error occured in the above code or not
// Write the status to the log textbox on the form (txtLog)
//this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "The file was received. Closing streams.\r\n" });
// Close the streams
strLocal.Close();
strRemote.Close();
// Write the status to the log textbox on the form (txtLog)
//this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "Streams are now closed.\r\n" });
// Start the server (TCP listener) all over again
StartReceiving();
}
}
private static void Title_Console(string title)
{
Console.BackgroundColor=ConsoleColor.DarkCyan;
Console.Clear();
Console.ForegroundColor=ConsoleColor.White;
Console.Title = title;
}
private static void Error_Message(string msg)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(msg);
Console.ForegroundColor = ConsoleColor.White;
}
/// <summary>
/// Отключение клиента от сервера
/// </summary>
public void DisconnectClient()
{
strRemote.Close();
strLocal.Close();
_tcpClient.Close();
}
/// <summary>
/// Завершение работы подключенного клиента
/// </summary>
private void DeleteClient()
{
if (_tcpClient != null && _tcpClient.Connected == true)
{
_tcpClient.GetStream().Close(); // по настоянию MSDN закрываем поток отдельно у клиента
_tcpClient.Close(); // затем закрываем самого клиента
}
}
}
}using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Windows.Forms;
using Security_file_link;
namespace WindowsFormsApplication_Server_Files
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DialogInfo dialog=new DialogInfo();
//Server_Client_Files_Send serverClient=new Server_Client_Files_Send();
private string path_tmp { get; set; }
private void button1_Click(object sender, EventArgs e)
{
string path = dialog.openfiledialog("files|*.*", "Выбрать файл", "");
label1.Text = Path.GetFileName(path);
path_tmp = path;
}
// The TCP client will connect to the server using an IP and a port
TcpClient tcpClient;
// The file stream will read bytes from the local file you are sending
FileStream fstFile;
// The network stream will send bytes to the server application
NetworkStream strRemote;
private void button2_Click(object sender, EventArgs e)
{
try
{
tcpClient = new TcpClient();
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
tcpClient.Connect(ipEndPoint);
label2.Text = "Connect Server...";
}
catch (Exception ex)
{
MessageBox.Show("ERROR: "+ex.Message,"ERROR",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}
}
private void button3_Click(object sender, EventArgs e)
{
label2.Text = "Send File";
strRemote = tcpClient.GetStream();
byte[] byteSend = new byte[tcpClient.ReceiveBufferSize];
// The file stream will read bytes from the file that the user has chosen
fstFile = new FileStream(path_tmp, FileMode.Open, FileAccess.Read);
// Read the file as binary
BinaryReader binFile = new BinaryReader(fstFile);
// Get information about the opened file
FileInfo fInfo = new FileInfo(path_tmp);
// Get and store the file name
string FileName = fInfo.Name;
// Store the file name as a sequence of bytes
byte[] ByteFileName = new byte[2048];
ByteFileName = System.Text.Encoding.ASCII.GetBytes(FileName.ToCharArray());
// Write the sequence of bytes (the file name) to the network stream
strRemote.Write(ByteFileName, 0, ByteFileName.Length);
// Get and store the file size
long FileSize = fInfo.Length;
// Store the file size as a sequence of bytes
byte[] ByteFileSize = new byte[2048];
ByteFileSize = System.Text.Encoding.ASCII.GetBytes(FileSize.ToString().ToCharArray());
// Write the sequence of bytes (the file size) to the network stream
strRemote.Write(ByteFileSize, 0, ByteFileSize.Length);
label2.Text += "Sending the file " + FileName + " (" + FileSize + " bytes)\r\n";
// Reset the number of read bytes
int bytesSize = 0;
// Define the buffer size
byte[] downBuffer = new byte[2048];
// Loop through the file stream of the local file
while ((bytesSize = fstFile.Read(downBuffer, 0, downBuffer.Length)) > 0)
{
// Write the data that composes the file to the network stream
strRemote.Write(downBuffer, 0, bytesSize);
}
// Update the log textbox and close the connections and streams
label2.Text += "File sent. Closing streams and connections.\r\n";
tcpClient.Close();
strRemote.Close();
fstFile.Close();
label2.Text += "Streams and connections are now closed.\r\n";
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}Решение задачи: «.NET 3.x TCP Клиент-Сервер, передача файлов, упрощение кода»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace SERVER_FILES_TEST
{
class Program
{
static TcpListener listner;
//Потоки
private static NetworkStream strRemote;
private static BinaryReader br;
private static BinaryWriter bw;
private static MemoryStream memoryStream;
static void Main(string[] args)
{
Title_Console("Сервер Файлов");
try
{
string ipstr = "127.0.0.1", portstr = "9050";
IPAddress ip = IPAddress.Parse(ipstr);
Int32 port = Convert.ToInt32(portstr);
IPEndPoint ipEndPoints = new IPEndPoint(ip, port);
Message_Console("IP: "+ip);
Message_Console("PORT: "+port);
listner = new TcpListener(ipEndPoints);
//запуск сервера
listner.Start();
Message_Console("Сервер запущен...");
//бесконеыный цикл приема и ответа
while (true)
{
string msg_client = string.Empty;
TcpClient client = listner.AcceptTcpClient();
//потоки обявляем
strRemote = client.GetStream();
br = new BinaryReader(strRemote);
bw = new BinaryWriter(strRemote);
//получаем от клиента
msg_client = Get_msg();
Message_Console("Клиент: "+msg_client);
Get_file(msg_client);
//отправить клиенту
Console.Write("Server: ");
Set_msg(Console.ReadLine());
}
}
catch (Exception ex)
{
Disconect_server();
Error_Message(ex.Message);
}
}
//отправляем
private static void Set_file()
{
}
private static void Set_msg(string msg)
{
bw.Write(msg);
}
//получаем
private static string Get_msg()
{
return br.ReadString();
}
private static void Get_file(string filename)
{
int bytesSize = 0;
byte[] buffer = new byte[2048];
try
{
//buffer = br.ReadBytes(0);
bytesSize = strRemote.Read(buffer, 0, 2048);
//поток файла
Stream strLocal = new FileStream(@"C:" + filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
//размер файла
long FileSize = Convert.ToInt64(System.Text.Encoding.ASCII.GetString(buffer, 0, bytesSize));
while ((bytesSize = strRemote.Read(buffer, 0, buffer.Length)) > 0)
{
// Write the data to the local file stream
strLocal.Write(buffer, 0, bytesSize);
// Update the progressbar by passing the file size and how much we downloaded so far to UpdateProgress()
}
Message_Console("Загрузка " + filename + " завершена!");
}
catch (Exception ex)
{
Error_Message(ex.Message);
}
}
//отключаем
private static void Disconect_server()
{
strRemote.Close();
br.Close();
bw.Close();
memoryStream.Close();
listner.Stop();
}
/////////////////Краска, Титулка, Паузы////////////////////////////
static void Title_Console(string title)
{
Console.BackgroundColor=ConsoleColor.DarkCyan;
Console.Clear();
Console.ForegroundColor=ConsoleColor.White;
Console.Title = title;
}
static void Pause()
{
Console.ReadKey(true);
}
static void Message_Console(string msg)
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(msg);
Console.ForegroundColor = ConsoleColor.White;
}
static void Error_Message(string msg)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(msg);
Console.ForegroundColor = ConsoleColor.White;
}
////////////////////////////////////////////////////////////////////
}
}