Windows send file tcp

Отправка файлов по сети

Отправка файлов по сети

Отправка файлов по сети имеет определенные особенности по сравнению с отправкой текстовых сообщений. Размер файла в большинстве случаев значительно больше текста и отправку (прием) вследствие этого необходимо осуществлять порциями. Более того при обмене файлами по сети необходимо кроме содержимого файла передавать информацию об его имени, типе (расширении) и возможно еще какие-либо дополнительные данные. Сетевой поток байтов в этом случае будет насыщен различной информацией, содержание которой можно узнать только после полной расшифровки.

Проблемы отправки

Разрабатывая сетевое приложение для отправки файлов по сети, сталкиваешься с трудностями надежного приема точного количества байтов при заранее неизвестном составе получаемого сетевого пакета. Используя при обмене сетевыми сообщениями принцип работы протокола TCP, разработанный умными людьми для надежной доставки информации, можно успешно обмениваться файлами и текстовыми сообщениями. Суть способа проста: вся необходимая информация содержится в самом пересылаемом пакете байтов в заранее известном месте.

Обеспечение надежности доставки данных

Подробнее: создается первый (главный заголовок) с информацией о последующих объектах сетевого потока. Главный заголовок имеет фиксированный размер для однозначной его интерпретации. После заголовка следует информационная структура с подробной информацией о присланных сетевых данных. Размер ее мы и указываем в главном заголовке. При успешной расшифровке (десериализации) информационной структуры мы получим точные данные, ведь такая структура может нести в себе текстовые, числовые и двоичные данные.

Краткий листинг передачи файлов

Краткий листинг получения файлов

Исходник отправки файлов по сети

Исходник построен на классах TcpListener и TcpClient упрощающих процесс создания сетевых приложений. Для сериализации в двоичный формат и обратной десериализации используется класс BinaryFormatter. Ограничений по размеру на пересылаемый файла в исходнике не установлен, максимальный размер зависит от производительности компьютера и объема оперативной памяти.

Среда программирования MS Visual Studio.NET 2010 и выше, открытая среда программирования для C# SharpDevelop 4.2 и выше, .NET Framework 3.0 и выше.

Скачать исходник

  • Файл: tcpsendfiles2_vs11.zip
  • Размер: 34 Кбайт
  • Загрузки: 4787

Похожая тематика

Сетевая программа на протоколе UDP »

Протокол TCP, отправка текстовых сообщений по сети »

Передача указателей в объектах классов и структур по сети »

send function (winsock2.h)

The send function sends data on a connected socket.

Syntax

Parameters

A descriptor identifying a connected socket.

A pointer to a buffer containing the data to be transmitted.

The length, in bytes, of the data in buffer pointed to by the buf parameter.

A set of flags that specify the way in which the call is made. This parameter is constructed by using the bitwise OR operator with any of the following values.

Value Meaning
MSG_DONTROUTE Specifies that the data should not be subject to routing. A Windows Sockets service provider can choose to ignore this flag.
MSG_OOB Sends OOB data (stream-style socket such as SOCK_STREAM only.

Return value

If no error occurs, send returns the total number of bytes sent, which can be less than the number requested to be sent in the len parameter. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError.

Читайте также:  Windows 10 не находит второй дисплей
Error code Meaning
WSANOTINITIALISED A successful WSAStartup call must occur before using this function.
WSAENETDOWN The network subsystem has failed.
WSAEACCES The requested address is a broadcast address, but the appropriate flag was not set. Call setsockopt with the SO_BROADCAST socket option to enable use of the broadcast address.
WSAEINTR A blocking Windows Sockets 1.1 call was canceled through WSACancelBlockingCall.
WSAEINPROGRESS A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
WSAEFAULT The buf parameter is not completely contained in a valid part of the user address space.
WSAENETRESET The connection has been broken due to the keep-alive activity detecting a failure while the operation was in progress.
WSAENOBUFS No buffer space is available.
WSAENOTCONN The socket is not connected.
WSAENOTSOCK The descriptor is not a socket.
WSAEOPNOTSUPP MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, OOB data is not supported in the communication domain associated with this socket, or the socket is unidirectional and supports only receive operations.
WSAESHUTDOWN The socket has been shut down; it is not possible to send on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH.
WSAEWOULDBLOCK The socket is marked as nonblocking and the requested operation would block.
WSAEMSGSIZE The socket is message oriented, and the message is larger than the maximum supported by the underlying transport.
WSAEHOSTUNREACH The remote host cannot be reached from this host at this time.
WSAEINVAL The socket has not been bound with bind, or an unknown flag was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled.
WSAECONNABORTED The virtual circuit was terminated due to a time-out or other failure. The application should close the socket as it is no longer usable.
WSAECONNRESET The virtual circuit was reset by the remote side executing a hard or abortive close. For UDP sockets, the remote host was unable to deliver a previously sent UDP datagram and responded with a «Port Unreachable» ICMP packet. The application should close the socket as it is no longer usable.
WSAETIMEDOUT The connection has been dropped, because of a network failure or because the system on the other end went down without notice.

Remarks

The send function is used to write outgoing data on a connected socket.

For message-oriented sockets (address family of AF_INET or AF_INET6, type of SOCK_DGRAM, and protocol of IPPROTO_UDP, for example), care must be taken not to exceed the maximum packet size of the underlying provider. The maximum message packet size for a provider can be obtained by calling getsockopt with the optname parameter set to SO_MAX_MSG_SIZE to retrieve the value of socket option. If the data is too long to pass atomically through the underlying protocol, the error WSAEMSGSIZE is returned, and no data is transmitted.

The successful completion of a send function does not indicate that the data was successfully delivered and received to the recipient. This function only indicates the data was successfully sent.

If no buffer space is available within the transport system to hold the data to be transmitted, send will block unless the socket has been placed in nonblocking mode. On nonblocking stream oriented sockets, the number of bytes written can be between 1 and the requested length, depending on buffer availability on both the client and server computers. The select, WSAAsyncSelect or WSAEventSelect functions can be used to determine when it is possible to send more data.

Читайте также:  Resetting windows 10 error

Calling send with a len parameter of zero is permissible and will be treated by implementations as successful. In such cases, send will return zero as a valid value. For message-oriented sockets, a zero-length transport datagram is sent.

The flags parameter can be used to influence the behavior of the function beyond the options specified for the associated socket. The semantics of the send function are determined by any options previously set on the socket specified in the s parameter and the flags parameter passed to the send function.

The order of calls made to send is also the order in which the buffers are transmitted to the transport layer. send should not be called on the same stream-oriented socket concurrently from different threads, because some Winsock providers may split a large send request into multiple transmissions, and this may lead to unintended data interleaving from multiple concurrent send requests on the same stream-oriented socket.

Example Code

Example Code

Notes for IrDA Sockets

  • The Af_irda.h header file must be explicitly included.

WindowsВ PhoneВ 8: This function is supported for Windows Phone Store apps on WindowsВ PhoneВ 8 and later.

WindowsВ 8.1 and Windows ServerВ 2012В R2: This function is supported for Windows Store apps on WindowsВ 8.1, Windows ServerВ 2012В R2, and later.

Send / receive file over TCP [duplicate]

I am trying to send a file from a server to a client over TCP.

Server-side code, sending file:

Client-side code, receive file:

Can someone point where I am getting it wrong ?

The file has 1036 kb, and it sends only 1032 kb and then gets stuck it won’t get out the while loop on the client-side.

Also if I close the server and open it really quick it sends the last bytes and the files sends completely. (this file opens perfectly)

I think it`s a problem on the server side not sending all the bytes but why and where.

1 Answer 1

Well this is a problem in your server-side code to start with:

You’re ignoring the value returned by Read . Never do that. With FileStream you’re possibly okay, but I personally wouldn’t trust it anyway. If you’re using .NET 4, you don’t need to do this anyway — just use Stream.CopyTo .

On the client-side code, your biggest initial problem is that you’re doing all of this on the UI thread. That’s a terrible idea — the UI will freeze if there’s a network glitch, as the Read call is blocking.

Again, just use Stream.CopyTo , but do it in a background thread.

Additionally, in all of these cases, use a using statement for the streams, so that you close them cleanly whatever happens.

That’s all just general hygiene. Now, as for why you’re hanging.

. you’re not closing the network stream on the server side. Therefore you never reach the end of the stream on the client side. If you only need to use the connection for a single file, then the answer is simple: just close the connection on the server side.

If, however, you need to use the same connection for multiple files, then you need more protocol — you need to some way of indicating the end of the data. There are three common ways of doing that:

  • Write the length of the data before the data itself, then on the reading side, first read the length, then read that many bytes, failing if the stream finishes before you’ve done so. This requires that you know how much data you’re going to write before you start writing.
  • Use an «end of data» marker which you can detect on the reading side; this is a pain in general, as it requires escaping the marker if it appears in the text itself.
  • A variation on the first approach, where you write a length-prefixed chunk at a time, then a zero-length chunk to indicate «end of data». This is pretty flexible, but obviously a bit more work than the first approach if the first approach actually works for you.
Читайте также:  Не грузиться windows без диска

Как отправить и получить сырые TCP и UDP данные

Передавать сырые данные TCP и UDP умеют программы Ncat, Netcat, nc.

В качестве сырых данных могут быть двоичные, для сохранения бинарных данных в файл можно использовать любой шестнадцатеричный редактор, например, Bless.

Как передавать и получать сырые данные по протоколу UDP

Чтобы не просто выполнить подключение, когда данные вводятся вручную (вводить шестнадцатеричные данные вручную затруднительно для нас), а чтобы подключиться и сразу передать данные, можно использовать команду вида:

Опция -u означает использовать UDP протокол (по умолчанию используется TCP).

Пример команды, которая отправляет данные из файла hello-camera.bin на удалённый IP 255.255.255.255 на UDP порт 34569:

UDP протокол не дожидается ответа, он разрывает соединение. Для отправки ответа удалённых хост запускает новое UDP соединение, но дело в том, что для его подключения мы должны прослушивать порт. Ответ придёт на UDP порт 34569. Прослушивать порт можно также командой ncat. Для этого используется команда вида:

В этой команде опция -u означает использовать UDP протокол (по умолчанию используется TCP). Опция -l означает прослушивать входящие соединения. IP-АДРЕС — это IP сетевого интерфейса на локальной машине, где запущена утилита ncat. ПОРТ — это порт для прослушивания.

IP адрес компьютера, где будет запущена ncat, 192.168.0.88, нужно прослушивать на 34569 порту, тогда команда следующая:

Кажется, что ничего не происходит, но программа и не завершает работу — она просто ожидает входящее соединение.

Не закрывая это окно терминала, откроем другую консоль и вновь повторяем первую команду:

После этого в первой консоли будет показан полученный ответ:

Чтобы сохранить присланный ответ (вместо того, чтобы выводить его на экран), можно использовать следующую команду для прослушивания входящих подключений:

В результате присланный ответ будет сохранён в файле response.bin.

Как передавать и получать сырые данные по протоколу TCP

Чтобы просто отправить сырые данные протоколом TCP в ncat, достаточно убрать опцию -u. Но в этом случае вы не получите ответа. Для того чтобы отправить данные и получить ответ нужно использовать конструкцию:

  • ФАЙЛ — это файл, содержащий данные для отправки
  • IP-АДРЕС — IP удалённого хоста, куда мы хотим отправить данные
  • ПОРТ — порт удалённого хоста, на который мы хотим отправить данные

Как можно увидеть, мы получили ответ.

Если вам нужно организовать «диалог» с удалённым хостом, то есть в рамках одной TCP сессии отправить несколько наборов данных, то данные для отправки запишите в отдельные файлы, например, если данные записаны в файлы ФАЙЛ1, ФАЙЛ2, ФАЙЛ3, ФАЙЛ4, тогда команда следующая:

Для своих целей я записал всех бинарные строки, которые отправляла программа CMS на камеру в отдельные файлы с именами hex1, hex2 и так далее до hex12. Для воспроизведения полного диалога с камерой можно использовать команду вида:

Оцените статью