2 /* $Id: pipe.cpp,v 1.4 2005-11-08 08:55:41 adam Exp $
3 Copyright (c) 2005, Index Data.
17 #include <netinet/in.h>
19 #include <arpa/inet.h>
20 #include <netinet/tcp.h>
26 #include <sys/socket.h>
29 #include <sys/select.h>
32 #include <boost/thread/thread.hpp>
33 #include <boost/thread/mutex.hpp>
34 #include <boost/thread/condition.hpp>
40 #include <yaz++/socket-observer.h>
46 class Pipe::Rep : public boost::noncopyable {
58 void Pipe::Rep::close(int &fd)
72 m_fd[0] = m_fd[1] = -1;
76 bool Pipe::Rep::nonblock(int s)
79 unsigned long tru = 1;
80 if (ioctlsocket(s, FIONBIO, &tru) < 0)
83 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0)
86 signal (SIGPIPE, SIG_IGN);
92 Pipe::Pipe(int port_to_use) : m_p(new Rep)
96 WORD wVersionRequested = MAKEWORD(2, 0);
97 if (WSAStartup( wVersionRequested, &wsaData ))
98 throw Pipe::Error("WSAStartup failed");
102 // create server socket
103 m_p->m_socket = socket(AF_INET, SOCK_STREAM, 0);
104 if (m_p->m_socket < 0)
105 throw Pipe::Error("could not create socket");
107 unsigned long one = 1;
108 if (setsockopt(m_p->m_socket, SOL_SOCKET, SO_REUSEADDR, (char*)
109 &one, sizeof(one)) < 0)
110 throw Pipe::Error("setsockopt error");
112 // bind server socket
113 struct sockaddr_in add;
114 add.sin_family = AF_INET;
115 add.sin_port = htons(port_to_use);
116 add.sin_addr.s_addr = INADDR_ANY;
117 struct sockaddr *addr = ( struct sockaddr *) &add;
119 if (bind(m_p->m_socket, addr, sizeof(struct sockaddr_in)))
120 throw Pipe::Error("could not bind on socket");
122 if (listen(m_p->m_socket, 3) < 0)
123 throw Pipe::Error("could not listen on socket");
127 tmpadd = (unsigned) inet_addr("127.0.0.1");
129 memcpy(&add.sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
131 throw Pipe::Error("inet_addr failed");
133 m_p->m_fd[1] = socket(AF_INET, SOCK_STREAM, 0);
134 if (m_p->m_fd[1] < 0)
135 throw Pipe::Error("could not create socket");
137 m_p->nonblock(m_p->m_fd[1]);
139 if (connect(m_p->m_fd[1], addr, sizeof(*addr)) < 0)
142 if (WSAGetLastError() != WSAEWOULDBLOCK)
143 throw Pipe::Error("could not connect to socket");
145 if (errno != EINPROGRESS)
146 throw Pipe::Error("could not connect to socket");
151 struct sockaddr caddr;
153 int caddr_len = sizeof(caddr);
155 socklen_t caddr_len = sizeof(caddr);
157 m_p->m_fd[0] = accept(m_p->m_socket, &caddr, &caddr_len);
158 if (m_p->m_fd[0] < 0)
159 throw Pipe::Error("could not accept on socket");
164 FD_SET(m_p->m_fd[1], &write_set);
165 int r = select(m_p->m_fd[1]+1, 0, &write_set, 0, 0);
167 throw Pipe::Error("could not complete connect");
169 m_p->close(m_p->m_socket);
181 m_p->close(m_p->m_fd[0]);
182 m_p->close(m_p->m_fd[1]);
183 m_p->close(m_p->m_socket);
189 int &Pipe::read_fd() const
194 int &Pipe::write_fd() const
202 * indent-tabs-mode: nil
203 * c-file-style: "stroustrup"
205 * vim: shiftwidth=4 tabstop=8 expandtab