Протокол TCP, отправка текстовых сообщений по сети
Сетевые приложения TCP
Исходные коды на C# клиентского и серверного приложения работающие по протоколуTCP. TCP — отличается от протокола UDP наличием постоянного соединения и гарантирующем доставку отправлений в неизменном виде. Приложения построены на высокоуровневых классах TcpListener , TcpClient . Данные классы инкапсулируют в себе более низкоуровневый Socket , предоставляя готовые настройки для прослушивающего сокета — TcpListener , и сокета создающего клиентское подключение — TcpClient .
Сетевой протокол TCP
TCP аббревиатура Transmission Control Protocol, протокол (правила) управления передачей. Протокол TCP разработан для надежной передачи данных через сеть компьютеров. TCP (протокол управления передачей) для своей функциональности требует наличие постоянного соединения между сетевыми процессами. Разбивая отсылаемое сообщение на части, называемые пакетами, TCP помечает их таким образом, что независимо от очереди доставки этих пакетов сообщение будет собрано точно, так как оно и было изначально. Причем при потере части данных механизм протокола управления передачей запросит потерянные пакеты повторно. При этом он ещё и проверяет целостность каждого пакета. История TCP официально начинается с 1974 года, с тех пор написано много технических статей тщательным образом анализирующих механизм функционирования TCP.
Приложение сервер
Серверное приложение способно принимать запросы на подключение от нескольких клиентов. Для подключения использует блокирующий метод класса TcpListener.AcceptTcpClient возвращающий объект класса TcpClient . Чтобы не задерживать работу интерфейса программы данный метод запускается в отдельном потоке, останавливающийся после подключения установленного максимального количества клиентов. При успешном подключении запускается поток извлечения сообщений для каждого клиента отдельно. Метод ответственный за прием сообщений ReceiveRun(object num) в качестве параметра получает индекс подключившегося клиента. Сервер после получения сообщения ретранслирует его всем подключившимся клиентам. Потоки извлечения сообщений работают до завершения работы приложения или до остановки сервера.
Извлечение сообщения от клиента и ретрансляция полученного сообщения другим клиентам
Клиент-приложение
Исходник клиентского приложения более простой. Функции его заключаются в подключении к серверу и приему-отправки сообщений. Используются только блокирующие методы, причем метод извлечения сообщений ReceiveRun() работает в вспомогательном потоке, а метод отправки сообщений SendMessage() в главном потоке, поскольку сообщения отправляются почти мгновенно и практически не блокируют интерфейс.
Безопасный доступ к интерфейсу формы осуществляем сформированным методом ShowReceiveMessage(string message) проверяющим свойство объекта Control.InvokeRequired и в случае если обращение к элементу формы осуществляется из другого потока вызываем Control.Invoke с делегатом в качестве первого параметра, через второй параметр можно передать любой объект. ShowReceiveMessage можно безопасно вызывать в любом потоке.
Краткий листинг клиентского приложения
Инструменты программирования и исходник
Примечание. Исходник отправки сообщений по протоколу TCP тестировался в Microsoft Visual Studio 2010, Операционная система Windows, .NET Framework 3.5 выше. При необходимости проект исходного кода конвертируется для работы в MS Visual Studio 2008.
The Windows Sockets socket function creates a socket which is bound to a specific service provider.
int af, int type, int protocol );
[in] An address family specification.
[in] A type specification for the new socket.
[in] A particular protocol to be used with the socket which is specific to the indicated address family.
The socket function causes a socket descriptor and any related resources to be allocated and bound to a specific transport service provider. Windows Sockets will utilize the first available service provider that supports the requested combination of address family, socket type and protocol parameters. Note that the socket created will have the overlapped attribute. Sockets without the overlapped attribute can only be created by using WSASocket.
Note The manifest constant AF_UNSPEC continues to be defined in the header file but its use is strongly discouraged, as this can cause ambiguity in interpreting the value of the protocol parameter.
The following are the only two type specifications supported for Windows Sockets 1.1:
Type Explanation SOCK_STREAM Provides sequenced, reliable, two-way, connection-based byte streams with an out-of-band data transmission mechanism. Uses TCP for the Internet address family. SOCK_DGRAM Supports datagrams, which are connectionless, unreliable buffers of a fixed (typically small) maximum length. Uses UDP for the Internet address family.
In Windows Sockets 2, many new socket types will be introduced. However, since an application can dynamically discover the attributes of each available transport protocol through the WSAEnumProtocols function, the various socket types need not be called out in the API specification. Socket type definitions will appear in WINSOCK2.H which will be periodically updated as new socket types, address families and protocols are defined. Connection-oriented sockets such as SOCK_STREAM provide full-duplex connections, and must be in a connected state before any data can be sent or received on it. A connection to another socket is created with a connect call. Once connected, data can be transferred using send and recv calls. When a session has been completed, a closesocket must be performed.
The communications protocols used to implement a reliable, connection-oriented socket ensure that data is not lost or duplicated. If data for which the peer protocol has buffer space cannot be successfully transmitted within a reasonable length of time, the connection is considered broken and subsequent calls will fail with the error code set to WSAETIMEDOUT. Connectionless, message-oriented sockets allow sending and receiving of datagrams to and from arbitrary peers using sendto and recvfrom. If such a socket is connected to a specific peer, datagrams can be sent to that peer using send and can be received only from this peer using recv.
Support for sockets with type RAW is not required, but service providers are encourage to support raw sockets whenever it makes sense to do so.
If no error occurs, socket returns a descriptor referencing the new socket. Otherwise, a value of INVALID_SOCKET is returned, and a specific error code can be retrieved by calling WSAGetLastError.
WSANOTINITIALISED A successful WSAStartup must occur before using this function. WSAENETDOWN The network subsystem or the associated service provider has failed. WSAEAFNOSUPPORT The specified address family is not supported. WSAEINPROGRESS A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function. WSAEMFILE No more socket descriptors are available. WSAENOBUFS No buffer space is available. The socket cannot be created. WSAEPROTONOSUPPORT The specified protocol is not supported. WSAEPROTOTYPE The specified protocol is the wrong type for this socket. WSAESOCKTNOSUPPORT The specified socket type is not supported in this address family.
The Windows Sockets socket function creates a socket which is bound to a specific service provider.
int af, int type, int protocol );
[in] An address family specification.
[in] A type specification for the new socket.
[in] A particular protocol to be used with the socket which is specific to the indicated address family.
The socket function causes a socket descriptor and any related resources to be allocated and bound to a specific transport service provider. Windows Sockets will utilize the first available service provider that supports the requested combination of address family, socket type and protocol parameters. Note that the socket created will have the overlapped attribute. Sockets without the overlapped attribute can only be created by using WSASocket.
Note The manifest constant AF_UNSPEC continues to be defined in the header file but its use is strongly discouraged, as this can cause ambiguity in interpreting the value of the protocol parameter.
The following are the only two type specifications supported for Windows Sockets 1.1:
Type Explanation SOCK_STREAM Provides sequenced, reliable, two-way, connection-based byte streams with an out-of-band data transmission mechanism. Uses TCP for the Internet address family. SOCK_DGRAM Supports datagrams, which are connectionless, unreliable buffers of a fixed (typically small) maximum length. Uses UDP for the Internet address family.
In Windows Sockets 2, many new socket types will be introduced. However, since an application can dynamically discover the attributes of each available transport protocol through the WSAEnumProtocols function, the various socket types need not be called out in the API specification. Socket type definitions will appear in WINSOCK2.H which will be periodically updated as new socket types, address families and protocols are defined. Connection-oriented sockets such as SOCK_STREAM provide full-duplex connections, and must be in a connected state before any data can be sent or received on it. A connection to another socket is created with a connect call. Once connected, data can be transferred using send and recv calls. When a session has been completed, a closesocket must be performed.
The communications protocols used to implement a reliable, connection-oriented socket ensure that data is not lost or duplicated. If data for which the peer protocol has buffer space cannot be successfully transmitted within a reasonable length of time, the connection is considered broken and subsequent calls will fail with the error code set to WSAETIMEDOUT. Connectionless, message-oriented sockets allow sending and receiving of datagrams to and from arbitrary peers using sendto and recvfrom. If such a socket is connected to a specific peer, datagrams can be sent to that peer using send and can be received only from this peer using recv.
Support for sockets with type RAW is not required, but service providers are encourage to support raw sockets whenever it makes sense to do so.
If no error occurs, socket returns a descriptor referencing the new socket. Otherwise, a value of INVALID_SOCKET is returned, and a specific error code can be retrieved by calling WSAGetLastError.
WSANOTINITIALISED A successful WSAStartup must occur before using this function. WSAENETDOWN The network subsystem or the associated service provider has failed. WSAEAFNOSUPPORT The specified address family is not supported. WSAEINPROGRESS A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function. WSAEMFILE No more socket descriptors are available. WSAENOBUFS No buffer space is available. The socket cannot be created. WSAEPROTONOSUPPORT The specified protocol is not supported. WSAEPROTOTYPE The specified protocol is the wrong type for this socket. WSAESOCKTNOSUPPORT The specified socket type is not supported in this address family.