socket_channel.cpp
Go to the documentation of this file.
00001 
00002 
00003 
00004 
00005 
00006 
00007 
00008 
00009 
00010 
00011 #include <opc/ua/socket_channel.h>
00012 #include <opc/ua/errors.h>
00013 
00014 
00015 #include <errno.h>
00016 #include <iostream>
00017 
00018 #include <stdexcept>
00019 #include <string.h>
00020 
00021 #include <sys/types.h>
00022 
00023 
00024 #ifdef _WIN32
00025 #include <WinSock2.h>
00026 #else
00027 #include <arpa/inet.h>
00028 #include <netinet/tcp.h>
00029 #include <sys/socket.h>
00030 #include <unistd.h>
00031 #endif
00032 
00033 
00034 OpcUa::SocketChannel::SocketChannel(int sock)
00035   : Socket(sock)
00036 {
00037   int flag = 1;
00038   setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int));
00039   if (Socket < 0)
00040   {
00041     THROW_ERROR(CannotCreateChannelOnInvalidSocket);
00042   }
00043 }
00044 
00045 OpcUa::SocketChannel::~SocketChannel()
00046 {
00047   Stop();
00048 }
00049 
00050 void OpcUa::SocketChannel::Stop()
00051 {
00052   int error = shutdown(Socket, 2);
00053   if (error < 0)
00054   {
00055     std::cerr << "Failed to close socket connection. " << strerror(errno) << std::endl;
00056   }
00057 }
00058 
00059 std::size_t OpcUa::SocketChannel::Receive(char* data, std::size_t size)
00060 {
00061   int received = recv(Socket, data, size, MSG_WAITALL);
00062   if (received < 0)
00063   {
00064     THROW_OS_ERROR("Failed to receive data from host.");
00065   }
00066   if (received == 0)
00067   {
00068     THROW_OS_ERROR("Connection was closed by host.");
00069   }
00070   return (std::size_t)size;
00071 }
00072 
00073 void OpcUa::SocketChannel::Send(const char* message, std::size_t size)
00074 {
00075   int sent = send(Socket, message, size, 0);
00076   if (sent != (int)size)
00077   {
00078     THROW_OS_ERROR("unable to send data to the host. ");
00079   }
00080 }


ros_opcua_impl_freeopcua
Author(s): Denis Štogl
autogenerated on Sat Jun 8 2019 18:24:56