Kenji Arai / TYBLE16_mbedlized_os5_several_examples_1st

Dependencies:   nRF51_Vdd TextLCD BME280

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers TCPServer.cpp Source File

TCPServer.cpp

00001 /* Socket
00002  * Copyright (c) 2015 ARM Limited
00003  *
00004  * Licensed under the Apache License, Version 2.0 (the "License");
00005  * you may not use this file except in compliance with the License.
00006  * You may obtain a copy of the License at
00007  *
00008  *     http://www.apache.org/licenses/LICENSE-2.0
00009  *
00010  * Unless required by applicable law or agreed to in writing, software
00011  * distributed under the License is distributed on an "AS IS" BASIS,
00012  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013  * See the License for the specific language governing permissions and
00014  * limitations under the License.
00015  */
00016 
00017 #include "TCPServer.h"
00018 
00019 using mbed::Callback;
00020 
00021 TCPServer::TCPServer()
00022 {
00023 }
00024 
00025 TCPServer::~TCPServer()
00026 {
00027 }
00028 
00029 nsapi_error_t TCPServer::accept(TCPSocket *connection, SocketAddress *address)
00030 {
00031     _lock.lock();
00032     nsapi_error_t ret;
00033 
00034     while (true) {
00035         if (!_socket) {
00036             ret = NSAPI_ERROR_NO_SOCKET ;
00037             break;
00038         }
00039 
00040         _pending = 0;
00041         void *socket;
00042         ret = _stack->socket_accept(_socket, &socket, address);
00043 
00044         if (0 == ret) {
00045             connection->_lock.lock();
00046 
00047             if (connection->_socket) {
00048                 connection->close();
00049             }
00050 
00051             connection->_stack = _stack;
00052             connection->_socket = socket;
00053             connection->_event = Callback<void()>(connection, &TCPSocket::event);
00054             _stack->socket_attach(socket, &Callback<void()>::thunk, &connection->_event);
00055 
00056             connection->_lock.unlock();
00057             break;
00058         } else if ((_timeout == 0) || (ret != NSAPI_ERROR_WOULD_BLOCK )) {
00059             break;
00060         } else {
00061             uint32_t flag;
00062 
00063             // Release lock before blocking so other threads
00064             // accessing this object aren't blocked
00065             _lock.unlock();
00066             flag = _event_flag.wait_any(READ_FLAG, _timeout);
00067             _lock.lock();
00068 
00069             if (flag & osFlagsError) {
00070                 // Timeout break
00071                 ret = NSAPI_ERROR_WOULD_BLOCK ;
00072                 break;
00073             }
00074         }
00075     }
00076 
00077     _lock.unlock();
00078     return ret;
00079 }