本文整理汇总了C++中TCPConnection类的典型用法代码示例。如果您正苦于以下问题:C++ TCPConnection类的具体用法?C++ TCPConnection怎么用?C++ TCPConnection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TCPConnection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: lock
/**
* Removes a connection from the bandwidth allocator
* Requests all other connections update their speed
*/
int BandwidthAllocator::removeBandwidth(TCPConnection* connection) {
boost::unique_lock<boost::mutex> lock(queueMutex);
// If we are not in a consistant state - wait
while(unsettled.size() > 0 || currentlyWorking) queueWaiting.wait(lock);
printf("1\n");
currentlyWorking = true;
int removeConnectionFd = connection->getSockFd();
int numConnections = settled.size();
int nodeSpeed = UPLINK_SPEED;
if (numConnections != 1) nodeSpeed = UPLINK_SPEED / (numConnections - 1);
printf("2\n");
TCPConnection* currentConnection;
for (int i = 0; i < numConnections; i++) {
currentConnection = settled.front();
settled.pop();
if (currentConnection->getSockFd() != removeConnectionFd) {
currentConnection->updateRemoteSpeed(nodeSpeed);
unsettled[currentConnection->getSockFd()] = currentConnection;
}
}
printf("3\n");
while(unsettled.size() > 0) queueWaiting.wait(lock);
printf("4\n");
currentlyWorking = false;
queueWaiting.notify_all();
printf("5\n");
return 0;
}
示例2: read_lines
bool HTTPServer_Impl::read_lines(TCPConnection &connection, std::string &out_header_lines)
{
out_header_lines.clear();
while (out_header_lines.length() < 32*1024)
{
char buffer[1024];
if (connection.get_read_event().wait(15000) == false)
throw Exception("Read timed out");
int bytes_read = connection.peek(buffer, 1024);
if (bytes_read <= 0)
break;
std::string str(buffer, bytes_read);
std::string::size_type start_pos = out_header_lines.length();
out_header_lines += str;
std::string::size_type pos = out_header_lines.find("\r\n\r\n");
if (pos == std::string::npos)
{
connection.receive(buffer, bytes_read);
}
else
{
connection.receive(buffer, pos+4-start_pos);
out_header_lines.resize(pos+4);
return true;
}
}
return false;
}
示例3: main
int main()
{
TCPConnection* pconnect = new TCPConnection();
pconnect->active_open();
pconnect->active_open();
pconnect->active_open();
pconnect->active_open();
pconnect->active_open();
}
示例4: TCPServer
Image Receive::apply(int port) {
// create and bind the server if it hasn't already been created
if (!servers[port]) {
servers[port] = new TCPServer(port);
}
printf("Listening on port %i\n", port);
TCPConnection *conn = servers[port]->listen();
printf("Got a connection, reading image...\n");
Image im = conn->recvImage();
delete conn;
return im;
}
示例5: main
int main()
{
//unsigned short port = 8080;
TCPConnection *MyConnection = new TCPConnection();
MyConnection->Listen();
MyConnection->Start();
while(1)
{
this_thread::sleep_for(std::chrono::milliseconds(1));
//sleep(5);
}
return 0;
}
示例6: send_request
void send_request(TCPConnection &connection)
{
std::string request =
"HEAD /index.html HTTP/1.1\r\n"
"Host: www.clanlib.org\r\n"
"\r\n";
NetworkConditionVariable wait_condition;
std::mutex mutex;
std::unique_lock<std::mutex> lock(mutex);
size_t pos = 0;
while (pos < request.length())
{
int bytes_written;
while (true)
{
bytes_written = connection.write(request.data() + pos, request.length() - pos);
if (bytes_written != -1)
break;
NetworkEvent *events[] = { &connection };
wait_condition.wait(lock, 1, events);
}
pos += bytes_written;
}
}
示例7: ThreadListen
void TCPConnection::ThreadListen(void* arg)
{
//printf("ThreadListe\n");
TCPConnection *MyClass = static_cast<TCPConnection*>(arg);
while(MyClass->mRunningListenFlag)
{
fd_set rfd; // read event
fd_set efd; // accept event
int retVal, nfds = 0;
timeval tv = { 0 };
tv.tv_usec = 1;
FD_ZERO(&rfd);
FD_ZERO(&efd);
FD_SET(MyClass->mSocketListener, &rfd);
nfds = nfds > MyClass->mSocketListener ? nfds : MyClass->mSocketListener;
FD_SET(MyClass->mSocketListener, &efd);
nfds = nfds > MyClass->mSocketListener ? nfds : MyClass->mSocketListener;
retVal = select(nfds + 1, &rfd, NULL, & efd, &tv);
if (retVal == -1 && errno == EINTR)
return ;
if (FD_ISSET(MyClass->mSocketListener, &efd))
{
char c;
retVal = recv(MyClass->mSocketListener, &c, 1, MSG_OOB);
}
if (FD_ISSET(MyClass->mSocketListener, &rfd))
{
//if(MyClass->mSocketPc == -1)
MyClass->OnAccept(MyClass->mSocketListener);
//else
//printf("Reject connection from PC !!!!\n");
}
}
}
示例8: while
void NetGameServer::listen_thread_main()
{
while (true)
{
std::unique_lock<std::mutex> lock(impl->mutex);
if (impl->stop_flag)
break;
NetworkEvent *events[] = { impl->tcp_listen.get() };
impl->worker_event.wait(lock, 1, events);
SocketName peer_endpoint;
TCPConnection connection = impl->tcp_listen->accept(peer_endpoint);
if (!connection.is_null())
{
std::unique_ptr<NetGameConnection> game_connection(new NetGameConnection(this, connection));
impl->connections.push_back(game_connection.release());
}
}
}
示例9: receive_response
DataBuffer receive_response(TCPConnection &connection)
{
std::array<char, 16000> response_data;
NetworkConditionVariable wait_condition;
std::mutex mutex;
std::unique_lock<std::mutex> lock(mutex);
size_t pos = 0;
while (pos < response_data.size())
{
size_t last_pos = pos > 0 ? pos - 4 : pos;
int bytes_read;
while (true)
{
bytes_read = connection.read(response_data.data() + pos, response_data.size() - pos);
if (bytes_read != -1)
break;
NetworkEvent *events[] = { &connection };
wait_condition.wait(lock, 1, events);
}
pos += bytes_read;
if (bytes_read == 0)
break;
bool end_header_found = false;
for (size_t i = last_pos; i + 3 < pos; i++)
{
if (response_data[i] == '\r' && response_data[i + 1] == '\n' && response_data[i + 2] == '\r' && response_data[i + 3] == '\n')
{
end_header_found = true;
break;
}
}
if (end_header_found)
break;
}
for (auto &line : StringHelp::split_text(std::string(response_data.data(), pos), "\r\n"))
{
Console::write_line(StringHelp::local8_to_text(line));
}
return DataBuffer();
}
示例10: run
void run()
{
const char* testData = "Twenty-five or six to four";
const size_t testDataLen = strlen(testData);
char* buff = reinterpret_cast<char*>(calloc(testDataLen + 1, 1));
const int port = 1337;
try {
// Create a listener and a client connection
TCPListener server(port);
TCPConnection client;
// Start the server and connect to it
server.start();
client.connect(IPEndPoint(IP(127, 0, 0, 1), port));
// Accept the connection
auto serverConn = server.accept();
// Test sending from the server to the client
serverConn->send(testData, testDataLen);
client.receive(buff, testDataLen);
if (strcmp(testData, buff) != 0)
throw TestFailedException("Data sent from server to client didn't go through properly");
// Reset the buffer and try sending from
// the client to the server
memset(buff, 0, testDataLen);
serverConn->shutDownSending();
client.shutDownReceiving();
client.send(testData, testDataLen);
serverConn->receive(buff, testDataLen);
if (strcmp(testData, buff) != 0)
throw TestFailedException("Data sent from client to server didn't go through properly");
// Shut down the connections
client.disconnect();
if (serverConn->receive(buff, testDataLen) != 0)
throw TestFailedException("The server was not notified when the client disconnected");
serverConn->disconnect();
free(buff);
}
catch (...) {
free(buff);
throw;
}
}
示例11: SetThreadPriority
ThreadReturnType TCPConnection::TCPConnectionLoop(void* tmp)
{
#ifdef _WINDOWS
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
#endif
if (tmp == 0)
{
THREAD_RETURN(nullptr);
}
TCPConnection* tcpc = (TCPConnection*) tmp;
#ifndef WIN32
//Log.Out(Logs::Detail, Logs::TCP_Connection, "%s Starting TCPConnectionLoop with thread ID %d", __FUNCTION__, pthread_self());
#endif
tcpc->MLoopRunning.lock();
while (tcpc->RunLoop())
{
Sleep(LOOP_GRANULARITY);
if (!tcpc->ConnectReady())
{
if (!tcpc->Process())
{
//the processing loop has detecting an error..
//we want to drop the link immediately, so we clear buffers too.
tcpc->ClearBuffers();
tcpc->Disconnect();
}
Sleep(1);
}
else if (tcpc->GetAsyncConnect())
{
tcpc->SetAsyncConnect(false);
}
else
{
Sleep(10); //nothing to do.
}
}
tcpc->MLoopRunning.unlock();
#ifndef WIN32
//Log.Out(Logs::Detail, Logs::TCP_Connection, "%s Ending TCPConnectionLoop with thread ID %d", __FUNCTION__, pthread_self());
#endif
THREAD_RETURN(nullptr);
}
示例12: run
void run(Thread *thread, void *args)
{
TCPConnection *conn = static_cast<TCPConnection *>(args);
conn->writeData();
}
示例13: write_line
void HTTPServer_Impl::write_line(TCPConnection &connection, const std::string &line)
{
connection.send(line.data(), line.length(), true);
connection.send("\r\n", 2, true);
}
示例14: connection_thread_main
void HTTPServer_Impl::connection_thread_main(TCPConnection connection)
{
try
{
std::string request;
bool bool_result = read_line(connection, request);
if (bool_result == false)
{
connection.disconnect_abortive();
return;
}
std::string headers;
bool_result = read_lines(connection, headers);
if (bool_result == false)
{
connection.disconnect_abortive();
return;
}
// Extract request command, url and version:
std::string command, url, version;
std::string::size_type pos1 = request.find(' ');
if (pos1 == std::string::npos)
throw Exception("Bad request");
command = request.substr(0, pos1);
if (command != "POST" && command != "GET")
throw Exception("Unsupported");
std::string::size_type pos2 = request.find(' ', pos1 + 1);
if (pos2 == std::string::npos)
throw Exception("Bad request");
url = request.substr(pos1+1, pos2-pos1-1);
std::string::size_type pos3 = request.find(' ', pos2 + 1);
if (pos3 != std::string::npos)
throw Exception("Bad request");
version = request.substr(pos2 + 1);
DataBuffer request_data;
// Handle request:
// Look for a request handler that will deal with the HTTP request:
MutexSection mutex_lock(&mutex);
std::vector<HTTPRequestHandler>::size_type index, size;
size = handlers.size();
bool handled = false;
for (index = 0; index < size; index++)
{
if (handlers[index].is_handling_request(command, url, headers))
{
HTTPRequestHandler handler = handlers[index];
mutex_lock.unlock();
if (command == "POST")
{
write_line(connection, "HTTP/1.1 100 Continue");
// write_line(connection, "Content-Length: 0");
write_line(connection, "");
}
std::shared_ptr<HTTPServerConnection_Impl> connection_impl(std::make_shared<HTTPServerConnection_Impl>());
connection_impl->connection = connection;
connection_impl->request_type = command;
connection_impl->request_url = url;
connection_impl->request_headers = headers;
HTTPServerConnection http_connection(connection_impl);
handler.handle_request(http_connection);
handled = true;
break;
}
}
mutex_lock.unlock();
if (!handled)
{
// No handler wants it. Reply with 404 Not Found:
std::string error_msg("404 Not Found");
write_line(connection, "HTTP/1.1 404 Not Found");
write_line(connection, "Server: ClanLib HTTP Server");
write_line(connection, "Connection: close");
write_line(connection, "Vary: *");
write_line(connection, "Content-Type: text/plain");
write_line(connection, "Content-Length: " + StringHelp::int_to_local8(error_msg.length()+2));
write_line(connection, "");
write_line(connection, error_msg);
}
connection.disconnect_graceful();
/*
if (url == "/")
{
File file("Sources/test.html", File::open_existing);
DataBuffer response(file.get_size());
file.read(response.get_data(), response.get_size(), true);
file.close();
// Send back response.
//.........这里部分代码省略.........
示例15: main
int main(int argc, char* argv[]){
gst_init(&argc,&argv);
char serverIP[SIZEOFCHARARRAY];
DataBaseAccess *dBA = new DataBaseAccess();
cout<<"\nCreate Main Function DBA\n";
dBA->ClearRtspTable();
if ( CheckValidation( dBA, serverIP ) ){
int channelCount = dBA->IsChannelsExist( dBA->GetSystemDID() );
Notification * notification = new Notification();
Retrieve * RetrieveObj = new Retrieve( serverIP, BroadCastStreamPortNumber, LocalStreamPortNumber );
RetrieveObj->StartThreadForVideoEntry(RetrieveObj);
VOD* VODObj = new VOD(serverIP, VODPortNumber );
BootLoader* BootLoaderObj = new BootLoader( RetrieveObj );
BootLoaderObj->StartBoot();
Failover * failover = new Failover(BootLoaderObj);
if ( channelCount == 0 ){
failover->StartThread(failover);
}
else
failover->isBreak = true;
Interaction * interaction = new Interaction(failover);
interaction->InitializeThread(interaction);
TCPConnection* TCPConnectionDesktop = new TCPConnection( tcpSocketPortNumber, RetrieveObj, VODObj, notification, false,failover,interaction );
if( !TCPConnectionDesktop->StartInternalThread() )
cout<<"Failed to create thread\n";
TCPConnection* TCPConnectionAndroid = new TCPConnection( AndroidTcpSocketPortNumber, RetrieveObj, VODObj, notification, true,failover,interaction );
if( !TCPConnectionAndroid->StartInternalThread() )
cout<<"Failed to create thread\n";
else
cout<<"\nTcp Connection Created\n";
usleep(5);
//Monitoring *monitoring = new Monitoring(dBA);
#if STARTPROCESSMONITORING
cout<<"\nStarting Monitoring\n";
Monitoring *monitoring;
monitoring = new Monitoring();
monitoring->StartInternalThread();
#endif
dBA->Close();
delete dBA;
cout<<"\n Close Main Function DBA\n";
TCPConnectionDesktop->WaitForInternalThreadToExit();
TCPConnectionAndroid->WaitForInternalThreadToExit();
delete VODObj;
delete TCPConnectionDesktop;
delete TCPConnectionAndroid;
delete interaction;
delete RetrieveObj;
delete failover;
delete BootLoaderObj;
delete notification;
}
else{
dBA->Close();
delete dBA;
}
return 0;
}