Передача файла по сети
От: Dark-Shadow  
Дата: 23.03.08 15:30
Оценка:
Пишу приложение передачи файла по сети, в принципе хоть код и жутко корявый но работает. Проблемма заключается в том что после принятия файла сервером он больше не принимает других соединений. а нужно чтоб он продолжал слушать порт и принимать другие приходящие файлы.

Код клиента:



using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace ConsoleClient
{
class Program
{
private static FileDetalis fileD = new FileDetalis();
private static IPAddress remoteAddres;
private const int remotePort = 5005;
private static UdpClient sender = new UdpClient();
private static IPEndPoint ipEndPoint;
private static FileStream fs;


[Serializable]
public class FileDetalis
{
public string FileType = "";
public long FileSize = 0;
}

static void Main(string[] args)
{
Console.WriteLine("Введите путь к фалу и его имя для отправки");
fs = new FileStream(@Console.ReadLine().ToString(), FileMode.Open, FileAccess.Read);
SendFileInfo();
Thread.Sleep(2000);
SendFileSize();
Thread.Sleep(2000);
byte[] bytes = new byte[Convert.ToInt32(fileD.FileSize)];
fs.Read(bytes, 0, bytes.Length);

TcpClient client = new TcpClient();
client.Connect("localhost", 5002);
NetworkStream stm = client.GetStream();



stm.Write(bytes, 0, bytes.Length);

}



public static void SendFileInfo()
{
try
{
remoteAddres = IPAddress.Parse("127.0.0.1");
ipEndPoint = new IPEndPoint(remoteAddres, remotePort);

fileD.FileType = fs.Name.Substring((int)fs.Name.Length — 3, 3);
fileD.FileSize = fs.Length;
string sb = fileD.FileType;

byte[] bytes = Encoding.ASCII.GetBytes(sb);
Console.WriteLine("Отправляется информация о файла");
sender.Send(bytes, bytes.Length, ipEndPoint);

}
catch { }
}

public static void SendFileSize()
{
try
{
remoteAddres = IPAddress.Parse("127.0.0.1");
ipEndPoint = new IPEndPoint(remoteAddres, remotePort);

fileD.FileType = fs.Name.Substring((int)fs.Name.Length — 3, 3);
fileD.FileSize = fs.Length;
byte[] byt = Encoding.ASCII.GetBytes(fileD.FileSize.ToString());
sender.Send(byt, byt.Length, ipEndPoint);
}
catch
{
}
}
}
}



Код сервера:



using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ConsoleApplication1
{
class Program
{
private static int localPort = 5005;
private static UdpClient rUdpClient = new UdpClient(localPort);
private static IPEndPoint rIpEnd = null;
private static byte[] rByte;
private static string fType;
private static string fSize;
private static FileStream fs;


static void Main(string[] args)
{
Console.WriteLine("Ждем получения файла");
Program pr = new Program();
pr.GetInfo();
Thread p = new Thread(new ThreadStart(pr.ReceivedFile));
p.Start();
Console.ReadLine();

}

private void GetInfo()
{
GetFileDet();
GetFileSize();
}
private void GetFileDet()
{
try
{

rByte = rUdpClient.Receive(ref rIpEnd);
Console.WriteLine("*****Тип файла*****");

fType = Encoding.ASCII.GetString(rByte);

Console.WriteLine(fType);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}

private void GetFileSize()
{
try
{
rByte = rUdpClient.Receive(ref rIpEnd);
Console.WriteLine("*****Размер файл*****");

fSize = Encoding.ASCII.GetString(rByte);

Console.WriteLine(fSize);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally { rUdpClient.Close(); }
}

private void ReceivedFile()
{

try
{
TcpListener listner = new TcpListener(5002);
listner.Start();
TcpClient client = listner.AcceptTcpClient();
NetworkStream st = client.GetStream();

rByte = new byte[Convert.ToInt32(fSize)];

st.Read(rByte, 0, Convert.ToInt32(fSize));
Console.WriteLine("Сохраняем присланый файл");

fs = new FileStream("temp." + fType, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
fs.Write(rByte, 0, rByte.Length);

Console.WriteLine("Файл сохранен");

}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

}
}
}




Помогите переделать код, или киньте ссылку на пример как это реализовать.

ЗЫ:

инфу о передаваемом файле передаю криво, серелизовать в xml незахотело.
... << RSDN@Home 1.1.4 stable SR1 rev. 568>>
Re: Передача файла по сети
От: Stuw  
Дата: 24.03.08 09:48
Оценка:
Здравствуйте, Dark-Shadow, Вы писали:


using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ConsoleApplication1
{
class Program
{
private static int localPort = 5005;
private static UdpClient rUdpClient = new UdpClient(localPort);
private static IPEndPoint rIpEnd = null;
private static byte[] rByte;
private static string fType;
private static string fSize;
private static FileStream fs;


static void Main(string[] args)
{
Console.WriteLine("Ждем получения файла");
Program pr = new Program();
pr.GetInfo();
Thread p = new Thread(new ThreadStart(pr.ReceivedFile));
p.Start();
Console.ReadLine();

}

private void GetInfo()
{
GetFileDet();
GetFileSize();
}
private void GetFileDet()
{
try
{

rByte = rUdpClient.Receive(ref rIpEnd);
Console.WriteLine("*****Тип файла*****");

fType = Encoding.ASCII.GetString(rByte);

Console.WriteLine(fType);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}

private void GetFileSize()
{
try
{
rByte = rUdpClient.Receive(ref rIpEnd);
Console.WriteLine("*****Размер файл*****");

fSize = Encoding.ASCII.GetString(rByte);

Console.WriteLine(fSize);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally { rUdpClient.Close(); }
}

private void ReceivedFile()
{

try
{ 
TcpListener listner = new TcpListener(5002);
listner.Start();
TcpClient client = listner.AcceptTcpClient();
NetworkStream st = client.GetStream();

rByte = new byte[Convert.ToInt32(fSize)];

st.Read(rByte, 0, Convert.ToInt32(fSize));
Console.WriteLine("Сохраняем присланый файл");

fs = new FileStream("temp." + fType, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
fs.Write(rByte, 0, rByte.Length);

Console.WriteLine("Файл сохранен");

}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

}
}
}


Код лучше оформлять специальными тегами (я твой код оформил тегом [ccode]).
1. Создаешь объект TcpListener. в цикле, при подключении клиентов (TcpClient client = listner.AcceptTcpClient();), для каждого клиента создаешь поток для приема файлов — для каждого клиента свой поток получается.
2. Создаешь поток в котором создаешь TcpListener и в цикле начинаешь принимать соединения (TcpClient client = listner.AcceptTcpClient();) и закачивать файлы — все файлы будут закачиваться в одном потоке, сначала от одного клиента, потом от другого и т.д.
Re[2]: Передача файла по сети
От: Dark-Shadow  
Дата: 24.03.08 10:58
Оценка:
Здравствуйте, Stuw, Вы писали:

Спасибо за совет. серверную часть передаелал пока что так:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ConsoleApplication1
{
    [Serializable]
    public class FileDetalis
    {
        public string FileType = "";
        public int FileSize = 0;
    }
    class Program
    {
        private static int localPort = 5005;
        private static UdpClient rUdpClient = new UdpClient(localPort);
        private static IPEndPoint rIpEnd = null;
        private static byte[] rByte;
        private static string fSize;
        private static FileStream fs;


        private static FileDetalis fdet;

        static void Main(string[] args)
        {
            Console.WriteLine("Ждем получения файла");

            Thread p = new Thread(new ThreadStart(ReceivedFile));
            p.Start();
            Console.ReadLine();

        }
       private static string Type;
        private static string Size;
        private static void GetFileInfo()
        {
                
                rByte = rUdpClient.Receive(ref rIpEnd);
                Console.WriteLine("*****Информация о файле*****");
                fSize = Encoding.ASCII.GetString(rByte);
                Type = fSize.Substring(0, 3);
                Size = fSize.Substring(3, fSize.Length - 3);
                Console.WriteLine(Type+"; "+Size);
                fdet = new FileDetalis();
                fdet.FileType = Type;
                fdet.FileSize = Convert.ToInt32(Size);
        }
        private static TcpClient client;
        public static void ReceivedFile()
        {

            try
            {
                
                TcpListener listner = new TcpListener(5002);

                listner.Start();
                while (true)
                {
                    client = listner.AcceptTcpClient();
                    if (client.Connected)
                    {
                        Thread tt = new Thread(new ThreadStart(Receiv));
                        tt.Start();
                    }

                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
        static void Receiv()
        {
            try
            {
                  GetFileInfo();
                  NetworkStream st = client.GetStream();
                rByte = new byte[Convert.ToInt32(Size)];

                st.Read(rByte, 0, rByte.Length);
                Console.WriteLine("Сохраняем присланый файл");

                fs = new FileStream("temp." + Type, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

                fs.Write(rByte, 0, rByte.Length);

                Console.WriteLine("Файл сохранен");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                fs.Close();
                client.Close();
            }
        }
    }
}


В принципе все работает. Но мне кажется (а точнее так оно и есть) мой код жутко корявый. Думаю многие сделалибы Намного красивее и легче

Спасибо за Совет!
... << RSDN@Home 1.1.4 stable SR1 rev. 568>>
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.