本文整理汇总了C++中Sock类的典型用法代码示例。如果您正苦于以下问题:C++ Sock类的具体用法?C++ Sock怎么用?C++ Sock使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Sock类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: putClassAdAndEOM
bool
putClassAdAndEOM(Sock & sock, classad::ClassAd &ad)
{
if (sock.type() != Stream::reli_sock)
{
return putClassAd(&sock, ad) && sock.end_of_message();
}
ReliSock & rsock = static_cast<ReliSock&>(sock);
Selector selector;
selector.add_fd(sock.get_file_desc(), Selector::IO_WRITE);
int timeout = sock.timeout(0); sock.timeout(timeout);
timeout = timeout ? timeout : 20;
selector.set_timeout(timeout);
if (!putClassAd(&sock, ad, PUT_CLASSAD_NON_BLOCKING))
{
return false;
}
int retval = rsock.end_of_message_nonblocking();
while (true) {
if (rsock.clear_backlog_flag()) {
Py_BEGIN_ALLOW_THREADS
selector.execute();
Py_END_ALLOW_THREADS
if (selector.timed_out()) {THROW_EX(RuntimeError, "Timeout when trying to write to remote host");}
} else if (retval == 1) {
示例2: sleep
void *threadGet(void *par)
{
struct BIS *pp = (struct BIS*) par;
Message m;
sleep(2);
Sock *sock = new Sock(SOCK_STREAM, 0);
SockDist *host = new SockDist(pp->ps->adresse, (short)pp->port);
if (connect(sock->getsDesc(),(sockaddr*)host->getAdrDist(), host->getsLen()) < 0)
{
perror("erreur connection");
}
int sockBis = sock->getsDesc();
char octet;
recv(sockBis, &octet, 1, 0);
if (octet == '0')
{
cout << "fichier inexistant" << endl;
return NULL;
}
cout << "début du transfert" << endl;
bool terminer = false;
struct timeval tt;
char buffer[TAILLE_BUFFER_MAX];
while (!terminer)
{
int nbr = 0;
int ret = 0;
fd_set readfs;
tt.tv_sec = 5;
tt.tv_usec = 0;
FD_ZERO(&readfs);
FD_SET(sockBis, &readfs);
ret = select(sockBis + 1, &readfs, NULL, NULL, &tt);
if (FD_ISSET(sockBis, &readfs))
{
nbr = recv(sockBis, buffer, TAILLE_BUFFER_MAX, 0);
pp->ps->fichierRecu.write(buffer, nbr);
}
if (ret <= 0)
{
pp->ps->fichierRecu.close();
close(sockBis);
delete sock;
delete host;
terminer = true;
cout << "fin de Get" << endl;
}
}
}
示例3: EvalXTCPRecv
void EvalXTCPRecv(const void *obj, qCtx *ctx, qStr *out, qArgAry *args)
{
Sock *s = (Sock *) obj;
int len;
char *line = NULL;
if (args->Count() > 0) {
len = ParseInt((*args)[0]);
len = s->Read(len);
line = s->GetBuf();
} else {
len = s->ReadLine(&line);
}
if (len > 0)
out->PutS(line, len);
else if (len < 0 ) {
if (len == Sock::ERR_TIMEOUT) {
ctx->ThrowF(out, 702, "Timeout while waiting to read data from host %s:%d, %y", s->GetHost(), s->GetPort());
} else {
ctx->ThrowF(out, 702, "Error while reading data from host %s:%d, %y", s->GetHost(), s->GetPort(), GetLastError());
}
}
}
示例4: CCBIDToString
void
CCBServer::ForwardRequestToTarget( CCBServerRequest *request, CCBTarget *target )
{
Sock *sock = target->getSock();
ClassAd msg;
msg.Assign( ATTR_COMMAND, CCB_REQUEST );
msg.Assign( ATTR_MY_ADDRESS, request->getReturnAddr() );
msg.Assign( ATTR_CLAIM_ID, request->getConnectID() );
// for easier debugging
msg.Assign( ATTR_NAME, request->getSock()->peer_description() );
MyString reqid_str;
CCBIDToString( request->getRequestID(), reqid_str);
msg.Assign( ATTR_REQUEST_ID, reqid_str );
sock->encode();
if( !msg.put( *sock ) || !sock->end_of_message() ) {
dprintf(D_ALWAYS,
"CCB: failed to forward request id %lu from %s to target "
"daemon %s with ccbid %lu\n",
request->getRequestID(),
request->getSock()->peer_description(),
target->getSock()->peer_description(),
target->getCCBID());
RequestFinished( request, false, "failed to forward request to target" );
return;
}
// Now wait for target to respond (HandleRequestResultsMsg).
// We will get the response next time we poll the socket.
// To get a faster response, we _could_ register the socket
// now, if it has not already been registered.
}
示例5: startCommand
bool
DCStartd::drainJobs(int how_fast,bool resume_on_completion,char const *check_expr,char const *start_expr,std::string &request_id)
{
std::string error_msg;
ClassAd request_ad;
Sock *sock = startCommand( DRAIN_JOBS, Sock::reli_sock, 20 );
if( !sock ) {
formatstr(error_msg,"Failed to start DRAIN_JOBS command to %s",name());
newError(CA_FAILURE,error_msg.c_str());
return false;
}
request_ad.Assign(ATTR_HOW_FAST,how_fast);
request_ad.Assign(ATTR_RESUME_ON_COMPLETION,resume_on_completion);
if( check_expr ) {
request_ad.AssignExpr(ATTR_CHECK_EXPR,check_expr);
}
if( start_expr ) {
request_ad.AssignExpr(ATTR_START_EXPR,start_expr);
}
if( !putClassAd(sock, request_ad) || !sock->end_of_message() ) {
formatstr(error_msg,"Failed to compose DRAIN_JOBS request to %s",name());
newError(CA_FAILURE,error_msg.c_str());
delete sock;
return false;
}
sock->decode();
ClassAd response_ad;
if( !getClassAd(sock, response_ad) || !sock->end_of_message() ) {
formatstr(error_msg,"Failed to get response to DRAIN_JOBS request to %s",name());
newError(CA_FAILURE,error_msg.c_str());
delete sock;
return false;
}
response_ad.LookupString(ATTR_REQUEST_ID,request_id);
bool result = false;
int error_code = 0;
response_ad.LookupBool(ATTR_RESULT,result);
if( !result ) {
std::string remote_error_msg;
response_ad.LookupString(ATTR_ERROR_STRING,remote_error_msg);
response_ad.LookupInteger(ATTR_ERROR_CODE,error_code);
formatstr(error_msg,
"Received failure from %s in response to DRAIN_JOBS request: error code %d: %s",
name(),error_code,remote_error_msg.c_str());
newError(CA_FAILURE,error_msg.c_str());
delete sock;
return false;
}
delete sock;
return true;
}
示例6: ParseDbl
void qObjProto::EvalXTCP(qCtx *ctx, qStr *out, qArgAry *args)
{
if (args->Count() < 1) {
ctx->Throw(out, 655, "USAGE: %connect-tcp(host,body[,timeout]])");
return;
}
CStrAry hosts;
CStr serv = (*args)[0];
CStr bodyStr = args->GetAt(1);
double timeout = ParseDbl((*args)[2]);
if (serv.IsEmpty())
return;
int port = 0;
char * p = strchr((const char *)serv, ':');
if (p) {
port = atoi(p+1);
*p = '\0';
++p;
}
if (!port)
port = IPPORT_TELNET;
int sock_rval;
Sock sock;
CStr body, dom, ref;
qCtxTmp tmpCtx(ctx);
if (!bodyStr.IsEmpty()) {
tmpCtx.MapObj(&sock, EvalXTCPSend,"send");
tmpCtx.MapObj(&sock, EvalXTCPRecv,"recv");
}
PROTO_OPEN_SOCK();
if (timeout > 1)
sock.SetTimeout((float) timeout);
tmpCtx.Parse(bodyStr, out);
sock.Close();
return;
}
示例7: EvalXTCPSend
void EvalXTCPSend(const void *obj, qCtx *ctx, qStr *out, qArgAry *args)
{
Sock *s = (Sock *) obj;
CStr str = (*args)[0];
int len = s->Write(str, str.Length());
if (len < 0 ) {
if (len == Sock::ERR_TIMEOUT) {
ctx->ThrowF(out, 702, "Timeout while waiting to write data from host %s:%d, %y", s->GetHost(), s->GetPort());
} else {
ctx->ThrowF(out, 702, "Error while writing data from host %s:%d, %y", s->GetHost(), s->GetPort(), GetLastError());
}
}
}
示例8: param
void
MachAttributes::credd_test()
{
// Attempt to perform a NOP on our CREDD_HOST. This will test
// our ability to authenticate with DAEMON-level auth, and thus
// fetch passwords. If we succeed, we'll advertise the CREDD_HOST
char *credd_host = param("CREDD_HOST");
if (credd_host == NULL) {
if (m_local_credd != NULL) {
free(m_local_credd);
m_local_credd = NULL;
}
return;
}
if (m_local_credd != NULL) {
if (strcmp(m_local_credd, credd_host) == 0) {
free(credd_host);
return;
}
else {
free(m_local_credd);
m_local_credd = NULL;
m_last_credd_test = 0;
}
}
time_t now = time(NULL);
double thresh = (double)param_integer("CREDD_TEST_INTERVAL", 300);
if (difftime(now, m_last_credd_test) > thresh) {
Daemon credd(DT_CREDD);
if (credd.locate()) {
Sock *sock = credd.startCommand(CREDD_NOP, Stream::reli_sock, 20);
if (sock != NULL) {
sock->decode();
if (sock->end_of_message()) {
m_local_credd = credd_host;
}
}
}
m_last_credd_test = now;
}
if (credd_host != m_local_credd) {
free(credd_host);
}
}
示例9: ASSERT
int
CCBListener::ReverseConnected(Stream *stream)
{
Sock *sock = (Sock *)stream;
ClassAd *msg_ad = (ClassAd *)daemonCore->GetDataPtr();
ASSERT( msg_ad );
if( sock ) {
daemonCore->Cancel_Socket( sock );
}
if( !sock || !sock->is_connected() ) {
ReportReverseConnectResult(msg_ad,false,"failed to connect");
}
else {
// The reverse-connect protocol is designed to look like a
// raw cedar command, in case the thing we are connecting
// to is a cedar command socket.
sock->encode();
int cmd = CCB_REVERSE_CONNECT;
if( !sock->put(cmd) ||
!msg_ad->put( *sock ) ||
!sock->end_of_message() )
{
ReportReverseConnectResult(msg_ad,false,"failure writing reverse connect command");
}
else {
((ReliSock*)sock)->isClient(false);
daemonCore->HandleReqAsync(sock);
sock = NULL; // daemonCore took ownership of sock
ReportReverseConnectResult(msg_ad,true);
}
}
delete msg_ad;
if( sock ) {
delete sock;
}
decRefCount(); // we incremented ref count when setting up callback
return KEEP_STREAM;
}
示例10: GetMyProxyPasswordFromSchedD
int GetMyProxyPasswordFromSchedD (int cluster_id, int proc_id,
char ** password)
{
// This might seem not necessary, but it IS
// For some reason you can't just pass cluster_id to sock->code() directly!!!!
int cluster, proc;
cluster = cluster_id;
proc = proc_id;
dprintf ( D_FULLDEBUG, " GetMyProxyPasswordFromSchedD %d, %d\n", cluster_id, proc_id);
// Get At Schedd
Daemon schedd( DT_SCHEDD );
if( ! schedd.locate() ) {
dprintf( D_ALWAYS, "GetMyProxyPasswordFromSchedD: Can't find address of local schedd\n" );
return FALSE;
}
// Start command
Sock* sock;
if (!(sock = schedd.startCommand( GET_MYPROXY_PASSWORD, Stream::reli_sock, 0))) {
dprintf( D_ALWAYS, "GetMyProxyPasswordFromSchedD: Could not connect to local schedd\n" );
return FALSE;
}
sock->encode();
if (!sock->code (cluster) || !sock->code(proc)) {
dprintf( D_ALWAYS, "GetMyProxyPasswordFromSchedD: Could not encode clusterId, procId\n" );
return FALSE;
}
sock->end_of_message();
sock->decode();
if (!sock->code (*password)) {
dprintf( D_ALWAYS, "GetMyProxyPasswordFromSchedD: Can't retrieve password\n" );
return FALSE;
}
sock->end_of_message();
sock->close();
delete sock;
return TRUE;
}
示例11: dprintf
void
CCBServer::SendHeartbeatResponse( CCBTarget *target )
{
Sock *sock = target->getSock();
ClassAd msg;
msg.Assign( ATTR_COMMAND, ALIVE );
sock->encode();
if( !msg.put( *sock ) || !sock->end_of_message() ) {
dprintf(D_ALWAYS,
"CCB: failed to send heartbeat to target "
"daemon %s with ccbid %lu\n",
target->getSock()->peer_description(),
target->getCCBID());
RemoveTarget( target );
return;
}
dprintf(D_FULLDEBUG,"CCB: sent heartbeat to target %s\n",
sock->peer_description());
}
示例12: daemon
bool
CCBListener::DoReversedCCBConnect( char const *address, char const *connect_id, char const *request_id, char const *peer_description )
{
Daemon daemon( DT_ANY, address );
CondorError errstack;
Sock *sock = daemon.makeConnectedSocket(
Stream::reli_sock,CCB_TIMEOUT,0,&errstack,true /*nonblocking*/);
ClassAd *msg_ad = new ClassAd;
ASSERT( msg_ad );
msg_ad->Assign( ATTR_CLAIM_ID, connect_id );
msg_ad->Assign( ATTR_REQUEST_ID, request_id );
// the following is put in the message because that is an easy (lazy)
// way to make it available to ReportReverseConnectResult
msg_ad->Assign( ATTR_MY_ADDRESS, address);
if( !sock ) {
// Failed to create socket or initiate connect
ReportReverseConnectResult(msg_ad,false,"failed to initiate connection");
delete msg_ad;
return false;
}
if( peer_description ) {
char const *peer_ip = sock->peer_ip_str();
if( peer_ip && !strstr(peer_description,peer_ip)) {
MyString desc;
desc.formatstr("%s at %s",peer_description,sock->get_sinful_peer());
sock->set_peer_description(desc.Value());
}
else {
sock->set_peer_description(peer_description);
}
}
incRefCount(); // do not delete self until called back
MyString sock_desc;
int rc = daemonCore->Register_Socket(
sock,
sock->peer_description(),
(SocketHandlercpp)&CCBListener::ReverseConnected,
"CCBListener::ReverseConnected",
this);
if( rc < 0 ) {
ReportReverseConnectResult(msg_ad,false,"failed to register socket for non-blocking reversed connection");
delete msg_ad;
delete sock;
decRefCount();
return false;
}
rc = daemonCore->Register_DataPtr(msg_ad);
ASSERT( rc );
return true;
}
示例13: execCommand
static void execCommand(Sock& sock, string& str, Buffer& buffer)
{
int ret;
uint16_t length = str.length();
ret = sock.send((const char*)& length, 2);
if (ret != 2) THROW("Failed to send command's length");
ret = sock.send(str.c_str(), length);
if (ret != length) THROW("Failed to send command");
ret = sock.receive((char*) &length, 2);
if (ret != 2) THROW("Failed to receive response length");
if (buffer.size() < length) {
buffer.extend(length - buffer.size() + 1);
}
buffer.clear();
ret = sock.receive(buffer.raw(), length);
if (ret != length) THROW("Failed to receive response");
buffer.commit(length);
buffer.closeText();
}
示例14: readHistoryRemote
// Read history from a remote schedd
static void readHistoryRemote(classad::ExprTree *constraintExpr)
{
printHeader();
if(longformat && use_xml) {
std::string out;
AddClassAdXMLFileHeader(out);
printf("%s\n", out.c_str());
}
classad::ClassAd ad;
classad::ExprList *projList(new classad::ExprList());
classad::ExprTree *projTree = static_cast<classad::ExprTree*>(projList);
ad.Insert(ATTR_PROJECTION, projTree);
ad.Insert(ATTR_REQUIREMENTS, constraintExpr);
ad.InsertAttr(ATTR_NUM_MATCHES, specifiedMatch <= 0 ? -1 : specifiedMatch);
DCSchedd schedd(g_name.size() ? g_name.c_str() : NULL, g_pool.size() ? g_pool.c_str() : NULL);
if (!schedd.locate(Daemon::LOCATE_FOR_LOOKUP)) {
fprintf(stderr, "Unable to locate remote schedd (name=%s, pool=%s).\n", g_name.c_str(), g_pool.c_str());
exit(1);
}
Sock* sock;
if (!(sock = schedd.startCommand(QUERY_SCHEDD_HISTORY, Stream::reli_sock, 0))) {
fprintf(stderr, "Unable to send history command to remote schedd;\n"
"Typically, either the schedd is not responding, does not authorize you, or does not support remote history.\n");
exit(1);
}
classad_shared_ptr<Sock> sock_sentry(sock);
if (!putClassAd(sock, ad) || !sock->end_of_message()) {
fprintf(stderr, "Unable to send request to remote schedd; likely a server or network error.\n");
exit(1);
}
while (true) {
compat_classad::ClassAd ad;
if (!getClassAd(sock, ad)) {
fprintf(stderr, "Failed to recieve remote ad.\n");
exit(1);
}
long long intVal;
if (ad.EvaluateAttrInt(ATTR_OWNER, intVal) && (intVal == 0)) { // Last ad.
if (!sock->end_of_message()) {
fprintf(stderr, "Unable to close remote socket.\n");
}
sock->close();
std::string errorMsg;
if (ad.EvaluateAttrInt(ATTR_ERROR_CODE, intVal) && intVal && ad.EvaluateAttrString(ATTR_ERROR_STRING, errorMsg)) {
fprintf(stderr, "Error %lld: %s\n", intVal, errorMsg.c_str());
exit(intVal);
}
if (ad.EvaluateAttrInt("MalformedAds", intVal) && intVal) {
fprintf(stderr, "Remote side had parse errors on history file");
exit(1);
}
if (!ad.EvaluateAttrInt(ATTR_NUM_MATCHES, intVal) || (intVal != matchCount)) {
fprintf(stderr, "Client and server do not agree on number of ads sent;\n"
"Indicates lost network packets or an internal error\n");
exit(1);
}
break;
}
matchCount++;
printJob(ad);
}
if(longformat && use_xml) {
std::string out;
AddClassAdXMLFileFooter(out);
printf("%s\n", out.c_str());
}
}
示例15: ProtoParseHosts
void qObjProto::EvalWhois(qCtx *ctx, qStr *out, qArgAry *args)
{
if (args->Count() < 1) {
ctx->Throw(out, 655, "USAGE: %whois(host[;host;host...][,body[,server[,bindip]]])");
return;
}
CStrAry hosts;
CStr hostStr = (*args)[0];
CStr bodyStr = (*args)[1];
CStr serv = (*args)[2];
CStr bindip = (*args)[3];
ProtoParseHosts(hosts, hostStr);
if (hosts.Count() == 0)
return;
int port;
if(serv.IsEmpty())
serv = DEFAULT_WHOIS_HOST;
port = IPPORT_WHOIS;
int sock_rval, i;
Sock sock;
if(!bindip.IsEmpty())
sock.Bind(bindip);
CStr body, dom, ref, reg, url;
qCtxTmp tmpCtx(ctx);
if (!bodyStr.IsEmpty()) {
tmpCtx.MapObj(&body, "results");
tmpCtx.MapObj(&body, "body");
tmpCtx.MapObj(&dom, "domain");
tmpCtx.MapObj(&ref, "refer");
tmpCtx.MapObj(&dom, "domain-name");
tmpCtx.MapObj(®, "registrar");
tmpCtx.MapObj(&ref, "whois-server");
tmpCtx.MapObj(&url, "referral-url");
}
for (i = 0; i < hosts.Count(); ++i) {
PROTO_OPEN_SOCK();
body = CStr();
ref = CStr();
dom = hosts[i];
sock.Write(hosts[i]<<"\r\n", hosts[i].Length()+2);
do {
if ((sock_rval = sock.Read(SOCK_DEFAULT_BUF_SIZE)) < 0) {
if (sock_rval == Sock::ERR_TIMEOUT)
ctx->ThrowF(out, 705, "Time out while reading from host %s:%d, %y", (const char *) serv, port, GetLastError());
else if (sock_rval)
ctx->ThrowF(out, 706, "Error reading from host %s:%d, %y", (const char *) serv, port, GetLastError());
return;
}
if (!bodyStr.IsEmpty())
body << CStr(sock.GetBuf(), sock_rval);
else
out->PutS(sock.GetBuf(), sock_rval);
}
while( sock_rval > 0); // If something was received
if (!bodyStr.IsEmpty()) {
const char *p;
if ((p = stristr(body.GetBuffer(),"Whois Server:"))) {
p += 14;
while (isspace(*p)) ++p;
char *e = strchr(p, '\n');
ref = CStr(p, e-p);
}
if ((p = stristr(body.GetBuffer(),"Registrar:"))) {
p += 14;
while (isspace(*p)) ++p;
char *e = strchr(p, '\n');
reg = CStr(p, e-p);
}
if ((p = stristr(body.GetBuffer(),"Referral URL:"))) {
p += 14;
while (isspace(*p)) ++p;
char *e = strchr(p, '\n');
url = CStr(p, e-p);
}
tmpCtx.Parse(bodyStr, out);
}
sock.Close();
}
return;
}