OSDN Git Service

4da2cec3ad7c48fdf9e3b459addd475b6a64af2d
[android-x86/device-generic-goldfish-opengl.git] / shared / OpenglCodecCommon / TcpStream.cpp
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 <cutils/sockets.h>
18 #include <errno.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <string.h>
23
24 #ifndef _WIN32
25 #include <netinet/in.h>
26 #include <netinet/tcp.h>
27 #else
28 #include <ws2tcpip.h>
29 #endif
30
31 TcpStream::TcpStream(size_t bufSize) :
32     SocketStream(bufSize)
33 {
34 }
35
36 TcpStream::TcpStream(int sock, size_t bufSize) :
37     SocketStream(sock, bufSize)
38 {
39     // disable Nagle algorithm to improve bandwidth of small
40     // packets which are quite common in our implementation.
41 #ifdef _WIN32
42     DWORD  flag;
43 #else
44     int    flag;
45 #endif
46     flag = 1;
47     setsockopt( sock, IPPROTO_TCP, TCP_NODELAY, (const char*)&flag, sizeof(flag) );
48 }
49
50 int TcpStream::listen(unsigned short port)
51 {
52     m_sock = socket_loopback_server(port, SOCK_STREAM);
53     if (!valid()) return int(ERR_INVALID_SOCKET);
54
55     return 0;
56 }
57
58 SocketStream * TcpStream::accept()
59 {
60     int clientSock = -1;
61
62     while (true) {
63         struct sockaddr_in addr;
64         socklen_t len = sizeof(addr);
65         clientSock = ::accept(m_sock, (sockaddr *)&addr, &len);
66
67         if (clientSock < 0 && errno == EINTR) {
68             continue;
69         }
70         break;
71     }
72
73     TcpStream *clientStream = NULL;
74
75     if (clientSock >= 0) {
76         clientStream =  new TcpStream(clientSock, m_bufsize);
77     }
78     return clientStream;
79 }
80
81 int TcpStream::connect(unsigned short port)
82 {
83     return connect("127.0.0.1",port);
84 }
85
86 int TcpStream::connect(const char* hostname, unsigned short port)
87 {
88     m_sock = socket_network_client(hostname, port, SOCK_STREAM);
89     if (!valid()) return -1;
90     return 0;
91 }