本文整理汇总了C++中TcpSocket::close方法的典型用法代码示例。如果您正苦于以下问题:C++ TcpSocket::close方法的具体用法?C++ TcpSocket::close怎么用?C++ TcpSocket::close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类TcpSocket
的用法示例。
在下文中一共展示了TcpSocket::close方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: readLinesFromClientTest
bool readLinesFromClientTest(const int linesize=TcpSocket::DEFAULT_MAX_MSG){
cout << "Starting readLinesFromClientTest(" << linesize << ") ...\n";
string message("Passaro verde abandona ninho. \nEscuto!\n");
pid_t child;
// client code
if ((child=fork())==0){
try {
TcpSocket toServer;
cout << " Forked child waiting a bit\n";
sleep(1);
cout << " Forked child connecting to server\n";
toServer.connect("127.0.0.1",LOCALPORT);
cout << " Forked child connected: " << toServer << endl;
cout << " Forked child sending to server\n";
toServer.writeline(message);
cout << " Forked child closing connection to server\n";
toServer.close();
cout << " Forked child exiting\n";
exit(0);
} catch (std::exception& e) {
cout << " Forked child exception: " << e.what() << endl;
exit(-1);
}
return false; // for clarity
}
// server code
TcpSocket* connectedSocket;
try {
TcpSocket serverSocket;
connectedSocket = bindListenAccept(LOCALPORT, serverSocket);
std::string clientmessage;
cout << " Reading one (at most " << linesize << " chars long) line from client\n";
// Read a line
connectedSocket->setMaxReceive(linesize);
while ((*connectedSocket) >> clientmessage);
if (clientmessage.empty())
throw std::runtime_error("clinet message is empty");
cout << " Read: \"" << clientmessage << "\"\n";
if (!(clientmessage.compare(message) == 0)){
throw std::runtime_error("Messages dont match");
}
checkChild(child);
serverSocket.close();
connectedSocket->close();
cout << "Done!\n";
delete connectedSocket;
return true;
} catch (std::exception& e) {
cout << " Server exception: " << e.what() << endl;
cout << "Failed!\n";
checkChild(child, true);
delete connectedSocket;
return false;
}
}
示例2: sendReceiveObjectTest
bool sendReceiveObjectTest(){
cout << "sendReceiveObjectTest() ...\n";
Object tosend('c', 34, true, "cinco");
pid_t child;
// client code
if ((child=fork())==0){
try {
TcpSocket toServer;
cout << " Forked child waiting a bit\n";
sleep(1);
cout << " Forked child connecting to server\n";
toServer.connect("127.0.0.1",LOCALPORT);
cout << " Forked child connected: " << toServer << endl;
cout << " Forked child sending to server\n";
toServer.write(reinterpret_cast<char *>(&tosend), sizeof(Object));
cout << " Forked child closing connection to server\n";
toServer.close();
cout << " Forked child exiting\n";
exit(0);
} catch (std::exception& e) {
cout << " Forked child exception: " << e.what() << endl;
exit(-1);
}
return false; // for clarity
}
// server code
TcpSocket* connectedSocket;
try {
TcpSocket serverSocket;
connectedSocket = bindListenAccept(LOCALPORT, serverSocket);
std::string clientmessage;
cout << " Reading one object from client\n";
// Read the object
Object received;
int len = connectedSocket->read(reinterpret_cast<char *>(&received), sizeof(Object));
cout << " Read: " << len << " bytes from " << *connectedSocket << endl;
if (!(tosend.compare(received) == 0))
throw std::runtime_error("objects dont match");
cout << " Server read " << received << endl;
checkChild(child);
serverSocket.close();
connectedSocket->close();
cout << "Done!\n";
delete connectedSocket;
return true;
} catch (std::exception& e) {
cout << " Server exception: " << e.what() << endl;
cout << "Failed!\n";
checkChild(child, true);
delete connectedSocket;
return false;
}
}
示例3: dabInputSlipThread
void* dabInputSlipThread(void* args)
{
dabInputSlipData* data = (dabInputSlipData*)args;
TcpSocket* client;
while ((client = data->server->accept()) != NULL) {
int size = 0;
etiLog.log(info, "SLIP server got a new client.\n");
#ifdef _WIN32
WaitForSingleObject(data->semWrite, INFINITE);
WaitForSingleObject(data->semQueue, INFINITE);
#else
sem_wait(&data->semWrite);
sem_wait(&data->semQueue);
#endif
UdpPacket* packet = data->packets[data->nbPackets];
#ifdef _WIN32
ReleaseSemaphore(data->semQueue, 1, NULL);
#else
sem_post(&data->semQueue);
#endif
while ((size = client->read(packet->getData(), packet->getSize()))
> 0) {
packet->setLength(size);
#ifdef _WIN32
WaitForSingleObject(data->semQueue, INFINITE);
#else
sem_wait(&data->semQueue);
#endif
data->nbPackets++;
#ifdef _WIN32
ReleaseSemaphore(data->semQueue, 1, NULL);
#else
sem_post(&data->semQueue);
#endif
#ifdef _WIN32
WaitForSingleObject(data->semWrite, INFINITE);
WaitForSingleObject(data->semQueue, INFINITE);
#else
sem_wait(&data->semWrite);
sem_wait(&data->semQueue);
#endif
packet = data->packets[data->nbPackets];
#ifdef _WIN32
ReleaseSemaphore(data->semQueue, 1, NULL);
#else
sem_post(&data->semQueue);
#endif
}
etiLog.log(info, "SLIP server client deconnected.\n");
client->close();
}
etiLog.log(error, "SLIP thread can't accept new client (%s)\n",
inetErrDesc, inetErrMsg);
return NULL;
}
示例4: simpleAcceptConnectTest
bool simpleAcceptConnectTest(){
cout << "Starting simpleAcceptConnectTest() ...\n";
pid_t child;
// client code
if ((child=fork())==0){
try {
TcpSocket toServer;
cout << " Forked child waiting a bit\n";
sleep(1);
cout << " Forked child connecting to server\n";
toServer.connect("127.0.0.1",LOCALPORT);
cout << " Forked child connected: " << toServer << endl;
cout << " Forked child closing connection to server\n";
toServer.close();
cout << " Forked child exiting\n";
exit(0);
} catch (TcpSocket::SocketException& e) {
cout << " Forked child exception: " << e.what() << endl;
exit(-1);
}
return false; // for clarity
}
// server code
TcpSocket* toClient;
try {
TcpSocket serverSocket;
toClient = bindListenAccept(LOCALPORT, serverSocket);
cout << " Server closing connection to client\n";
toClient->close();
cout << " Server closing listening socket\n";
serverSocket.close();
checkChild(child);
cout << "Done!\n";
delete toClient;
return true;
} catch (std::exception& e) {
cout << " Server exception: " << e.what() << endl;
cout << "Failed!\n";
checkChild(child, true);
delete toClient;
return false;
}
}
示例5: main
int main(void) {
TcpSocket servSocket;
servSocket.create();
servSocket.connect("127.0.0.1", 9999);
Message msg;
msg.add("type", "login");
msg.add("user", "root");
msg.add("pwd", "root");
servSocket << msg;
servSocket.close();
return 0;
}
示例6: catch
bool
HttpServer::send_response(TcpSocket &cl_sock, Yb::ILogger &logger,
int code, const string &desc, const string &body,
const string &cont_type)
{
try {
ostringstream out;
out << "HTTP/1.0 " << code << " " << desc
<< "\nContent-Type: " << cont_type
<< "\nContent-Length: " << body.size()
<< "\n\n" << body;
logger.debug("HTTP response:\n" + out.str());
cl_sock.write(out.str());
cl_sock.close(true);
return true;
}
catch (const std::exception &ex) {
logger.error(string("exception: ") + ex.what());
return false;
}
}
示例7: main
int main()
{
TcpServer server;
if (server.listen(2000) != AbstractSocket::Done)
{
perror("Error :");
return -1;
}
TcpSocket* s = server.accept();
if (s == NULL)
{
cout << "Error: cannot accept conection" << endl;
return -1;
}
cout << "Connected client" << endl;
int i = 4;
i++;
cout << "Remote host : " << s->getRemotePort() << endl;
cout << s->getLocalPort() << endl;
cout << server.getRemoteAddress().toString() << endl;
cout << s->getRemoteAddress().toString() << endl;
s->sendInt32(10);
sleep(2);
s->sendString("hello");
s->sendCharArray("world", 5);
Frame f;
f << "This is a frame " << 666 << '\n';
if (s->sendFrame(f) != AbstractSocket::Done)
perror("error on send frame");
delete s;
server.close();
s->close();
return 1;
}
示例8: accept
Socket::Status TcpListener::accept(TcpSocket& socket)
{
// Make sure that we're listening
if (getHandle() == priv::SocketImpl::invalidSocket())
{
err() << "Failed to accept a new connection, the socket is not listening" << std::endl;
return Error;
}
// Accept a new connection
sockaddr_in address;
priv::SocketImpl::AddrLength length = sizeof(address);
SocketHandle remote = ::accept(getHandle(), reinterpret_cast<sockaddr*>(&address), &length);
// Check for errors
if (remote == priv::SocketImpl::invalidSocket())
return priv::SocketImpl::getErrorStatus();
// Initialize the new connected socket
socket.close();
socket.create(remote);
return Done;
}
示例9: HashMapShrPtr
ServiceManager::~ServiceManager()
{
uint32 maxTcpNum = m_tcpSktClrNum*m_perClrTcpSktNum;
for (uint32 i=0; (i<maxTcpNum && m_usingTcp); ++i)
{
TcpSocket* tcpSkt = (TcpSocket*)sTcpSktFList.get()->get(i);
if (tcpSkt)
{
tcpSkt->close();
tcpSkt->clean();
}
}
HashMapShrPtr hm = sSSLSktFList.getFls();
if (hm)
{
uint32 size = hm->arraySize();
for (uint32 i=0; i<size; ++i)
{
hm->lockWrite((ContextId)i, (ContextId)i);
std::map<ContextId, IFreeListShrPtr>& hmMap = hm->map(i);
for (std::map<ContextId, IFreeListShrPtr>::iterator itr=hmMap.begin(); itr!=hmMap.end(); ++itr)
{
uint32 maxSSLSktNum = itr->second->getClr() * itr->second->getPer();
for (uint32 j=0; (j<maxSSLSktNum && m_usingSSL); ++j)
{
SSLSocket* sslSkt = (SSLSocket*)itr->second->get(j);
if (sslSkt)
{
sslSkt->socket()->lowest_layer().close();
sslSkt->clean();
}
}
}
hm->unlockWrite((ContextId)i, (ContextId)i);
}
}
hm = HashMapShrPtr();
uint32 maxUdpSubNum = m_udpSubSktClrNum*m_perClrUdpSubSktNum;
for (uint32 i=0; (i<maxUdpSubNum && m_usingUdp); ++i)
{
UdpSubSocket* udpSubSkt = (UdpSubSocket*)sUdpSubSktFList.get()->get(i);
if (udpSubSkt)
{
udpSubSkt->close();
udpSubSkt->clean();
}
}
uint32 maxUdpNum = m_udpSktClrNum*m_perClrUdpSktNum;
for (uint32 i=0; (i<maxUdpNum && m_usingUdp); ++i)
{
UdpSocket* udpSkt = (UdpSocket*)sUdpSktFList.get()->get(i);
if (udpSkt)
{
udpSkt->socket()->close();
udpSkt->clean();
}
}
m_contexts.clear();
for (uint32 i=0; i<m_tcpAcptrSvcs.size(); ++i)
{
if (m_tcpAcptrSvcs[i])
delete m_tcpAcptrSvcs[i];
}
for (uint32 i=0; i<m_sslAcptrSvcs.size(); ++i)
{
if (m_sslAcptrSvcs[i])
delete m_sslAcptrSvcs[i];
}
for (uint32 i=0; i<m_udpAcptrSvcs.size(); ++i)
{
if (m_udpAcptrSvcs[i])
delete m_udpAcptrSvcs[i];
}
for (uint32 i=0; i<m_tcpSvcs.size(); ++i)
{
if (m_tcpSvcs[i])
delete m_tcpSvcs[i];
}
for (uint32 i=0; i<m_sslSvcs.size(); ++i)
{
if (m_sslSvcs[i])
delete m_sslSvcs[i];
}
for (uint32 i=0; i<m_udpSvcs.size(); ++i)
{
if (m_udpSvcs[i])
delete m_udpSvcs[i];
}
}
示例10: main
//.........这里部分代码省略.........
unsigned int packetSize = packet.decodeHeader(headerBuffer);
// 2) Read packet size
std::vector<unsigned char> payloadBuffer;
socket.read(payloadBuffer, packetSize);
packet.decodePayload(payloadBuffer);
// ---------------------------------------
// Decode configuration file
// ---------------------------------------
boost::shared_ptr<RobogenConfig> configuration =
ConfigurationReader::parseRobogenMessage(
packet.getMessage()->configuration());
if (configuration == NULL) {
std::cerr
<< "Problems parsing the configuration file. Quit."
<< std::endl;
exitRobogen(EXIT_FAILURE);
}
// ---------------------------------------
// Setup environment
// ---------------------------------------
boost::shared_ptr<Scenario> scenario =
ScenarioFactory::createScenario(configuration);
if (scenario == NULL) {
exitRobogen(EXIT_FAILURE);
}
std::cout
<< "-----------------------------------------------"
<< std::endl;
// ---------------------------------------
// Run simulations
// ---------------------------------------
Viewer *viewer = NULL;
if(visualize) {
viewer = new Viewer(startPaused);
}
unsigned int simulationResult = runSimulations(scenario,
configuration, packet.getMessage()->robot(),
viewer, rng);
if(viewer != NULL) {
delete viewer;
}
if (simulationResult == SIMULATION_FAILURE) {
exitRobogen(EXIT_FAILURE);
}
// ---------------------------------------
// Compute fitness
// ---------------------------------------
double fitness;
if (simulationResult == CONSTRAINT_VIOLATED) {
fitness = MIN_FITNESS;
} else {
fitness = scenario->getFitness();
}
std::cout << "Fitness for the current solution: " << fitness
<< std::endl << std::endl;
// ---------------------------------------
// Send reply to EA
// ---------------------------------------
boost::shared_ptr<robogenMessage::EvaluationResult> evalResultPacket(
new robogenMessage::EvaluationResult());
evalResultPacket->set_fitness(fitness);
evalResultPacket->set_id(packet.getMessage()->robot().id());
ProtobufPacket<robogenMessage::EvaluationResult> evalResult;
evalResult.setMessage(evalResultPacket);
std::vector<unsigned char> sendBuffer;
evalResult.forge(sendBuffer);
socket.write(sendBuffer);
} catch (boost::system::system_error& e) {
socket.close();
exitRobogen(EXIT_FAILURE);
}
}
} else {
std::cerr << "Cannot connect to client. Exiting." << std::endl;
socket.close();
exitRobogen(EXIT_FAILURE);
}
}
exitRobogen(EXIT_SUCCESS);
}
示例11: readClient
void Worker::readClient()
{
//if (disabled)
// return;
// This slot is called when the client sent data to the server. The
// server looks if it was a get request and sends a very simple HTML
// document back.
TcpSocket* socket = static_cast<TcpSocket*>(sender());
if(socket->bytesAvailable())
{
if ( socket->isNewSocket())
{
QByteArray incomingContent=socket->readAll();
http_parser_settings settings;
settings. on_message_begin=onMessageBegin;
settings. on_url=onUrl;
settings. on_header_field=onHeaderField;
settings. on_header_value=onHeaderValue;
settings. on_headers_complete=onHeadersComplete;
settings. on_body=onBody;
settings. on_message_complete=onMessageComplete;
http_parser_init(&m_parser,HTTP_REQUEST);
m_parser.data = socket;
size_t nparsed = http_parser_execute(&m_parser,&settings,incomingContent.constData(),incomingContent.count());
if(m_parser.upgrade)
{
qDebug()<<"upgrade";
}
else if(nparsed != static_cast<size_t>(incomingContent.count()))
{
qDebug()<<"nparsed:"<<nparsed<<"buffer size:"<<incomingContent.count();
}
else
{
//qDebug()<<"parsing seems to be succeed!";
}
socket->setRawHeader(incomingContent);
bool isBodySizeOK=false;
unsigned int bodySize = 0;
QSharedPointer<QString> contentLength = socket->getHeader().getHeaderInfo("Content-Length");
if (!contentLength.isNull())
{
bodySize = contentLength->toUInt(&isBodySizeOK);
if(isBodySizeOK==false)
{
bodySize=0;
}
}
socket->setTotalBytes(bodySize);
socket->notNew();
}
else
{
qDebug()<<"socket size:"<<socket->getTotalBytes()<<"current Size:"<<socket->getBytesHaveRead();
QByteArray incomingContent=socket->readAll();
socket->appendData(incomingContent);
}
if (socket->getBytesHaveRead() > (16*1024*1024))
{
socket->getResponse().setStatusCode(400);
socket->getResponse() << "maximum message size above 16mb.";
socket->getResponse().finish();
socket->waitForBytesWritten();
socket->close();
}
else
if(socket->isEof())
{
PathTreeNode::HttpVerb handlerType;
if(m_parser.method==HTTP_GET)
{
socket->getHeader().setHttpMethod(HttpHeader::HttpMethod::HTTP_GET);
handlerType=PathTreeNode::GET;
}
else if(m_parser.method==HTTP_POST)
{
socket->getHeader().setHttpMethod(HttpHeader::HttpMethod::HTTP_POST);
handlerType=PathTreeNode::POST;
}
else
{
qDebug()<<"not get and post"<<socket->atEnd()<<socket->bytesAvailable()<<socket->ConnectedState;
socket->close();
return;
//.........这里部分代码省略.........