1 /*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 #include "TcpStream.h"
17 #include "emugl/common/sockets.h"
18
19 #include <errno.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <string.h>
24
25 #ifndef _WIN32
26 #include <netinet/in.h>
27 #include <netinet/tcp.h>
28 #else
29 #include <ws2tcpip.h>
30 #endif
31
32 #define LISTEN_BACKLOG 4
33
TcpStream(size_t bufSize)34 TcpStream::TcpStream(size_t bufSize) : SocketStream(bufSize) {}
35
TcpStream(int sock,size_t bufSize)36 TcpStream::TcpStream(int sock, size_t bufSize) :
37 SocketStream(sock, bufSize) {
38 // disable Nagle algorithm to improve bandwidth of small
39 // packets which are quite common in our implementation.
40 emugl::socketTcpDisableNagle(sock);
41 }
42
listen(char addrstr[MAX_ADDRSTR_LEN])43 int TcpStream::listen(char addrstr[MAX_ADDRSTR_LEN]) {
44 m_sock = emugl::socketTcpLoopbackServer(0, SOCK_STREAM);
45 if (!valid())
46 return int(ERR_INVALID_SOCKET);
47
48 int port = emugl::socketGetPort(m_sock);
49 if (port < 0) {
50 ::close(m_sock);
51 return int(ERR_INVALID_SOCKET);
52 }
53
54 snprintf(addrstr, MAX_ADDRSTR_LEN - 1, "%hu", port);
55 addrstr[MAX_ADDRSTR_LEN-1] = '\0';
56
57 return 0;
58 }
59
accept()60 SocketStream * TcpStream::accept() {
61 int clientSock = emugl::socketAccept(m_sock);
62 if (clientSock < 0)
63 return NULL;
64
65 return new TcpStream(clientSock, m_bufsize);
66 }
67
connect(const char * addr)68 int TcpStream::connect(const char* addr) {
69 int port = atoi(addr);
70 m_sock = emugl::socketTcpLoopbackClient(port, SOCK_STREAM);
71 return valid() ? 0 : -1;
72 }
73
connect(const char * hostname,unsigned short port)74 int TcpStream::connect(const char* hostname, unsigned short port)
75 {
76 m_sock = emugl::socketTcpClient(hostname, port, SOCK_STREAM);
77 return valid() ? 0 : -1;
78 }
79