Страницы

Поиск по вопросам

воскресенье, 15 марта 2020 г.

Передача данных без сервера

#c_sharp #передача_данных


К программе нужно добавить функционал передачи данных между ноутбуками. Написана на С#.
Есть доступ к интернету через WiFi. Есть пара ноутбуков.


Как передать файл с одного на другой? 
Как найти ір адрес другого ноутбука?


Как вариант можно использовать торрент сеть, но тогда другой вопрос.
Как ее прикрутить к С# проекту?
    


Ответы

Ответ 1



Вы пытаетесь решить две раздельных проблемы (в каждой из которых "сервер" используется в своем смысле) Первая - поиск второго ноутбука. В этой проблеме "сервер" - это какая-то машина, которая знает про все ноутбуки, и к которой ноуты обращаются за списком других ноутов. От этого сервера можно избавится. В System.Net.PeerToPeer есть пачка классов для поддержки одноранговых сетей. Примеры слишком объемны чтобы привести их в ответе, но можете начать с MSDN Blogs: Writing Peer-to-Peer Applications Using .NET: Регистрация peer: PeerName peerName = new PeerName("MikesWebServer", PeerNameType.Secured); PeerNameRegistration pnReg = new PeerNameRegistration(); pnReg.PeerName = peerName; pnReg.Port = 80; //OPTIONAL //The properties set below are optional. You can register a PeerName without setting these properties pnReg.Comment = "up to 39 unicode char comment"; pnReg.Data = System.Text.Encoding.UTF8.GetBytes("A data blob associated with the name"); /* * OPTIONAL *The properties below are also optional, but will not be set (ie. are commented out) for this example *pnReg.IPEndPointCollection = // a list of all {IPv4/v6 address, port} pairs to associate with the peername *pnReg.Cloud = //the scope in which the name should be registered (local subnet, internet, etc) */ //Starting the registration means the name is published for others to resolve pnReg.Start(); Console.WriteLine("Registration of Peer Name: {0} complete.", peerName.ToString()); Console.WriteLine(); Console.WriteLine("Press any key to stop the registration and close the program"); Console.ReadKey(); pnReg.Stop(); Поиск и получение информации о зарегистрованных: // create a resolver object to resolve a peername PeerNameResolver resolver = new PeerNameResolver(); // the peername to resolve must be passed as the first command line argument to the application PeerName peerName = new PeerName(args[0]); // resolve the PeerName - this is a network operation and will block until the resolve completes PeerNameRecordCollection results = resolver.Resolve(peerName); // Display the data returned by the resolve operation Console.WriteLine("Results for PeerName: {0}", peerName); Console.WriteLine(); int count = 1; foreach (PeerNameRecord record in results) { Console.WriteLine("Record #{0} results...", count); Console.Write("Comment:"); if (record.Comment != null) { Console.Write(record.Comment); } Console.WriteLine(); Console.Write("Data:"); if (record.Data != null) { Console.Write(System.Text.Encoding.ASCII.GetString(record.Data)); } Console.WriteLine(); Console.WriteLine("Endpoints:"); foreach (IPEndPoint endpoint in record.EndPointCollection){ Console.WriteLine("\t Endpoint:{0}", endpoint); Console.WriteLine(); } count++; } Console.ReadKey(); Вторая - собственно передача файла. Тут "сервер" - это комп, принимающий входящее соединение. Или комп, отдающий файл. Т.к. к этому моменту у вас будет адрес второго ноута, то достаточно взять любой пример по работе с сокетами, вычитать файл как массив байт, и передать его на другую сторону вместо строки из примера. И если вдруг не заработает - оформить это отдельным вопросом.

Комментариев нет:

Отправить комментарий