• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C++ UdpSocket类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中UdpSocket的典型用法代码示例。如果您正苦于以下问题:C++ UdpSocket类的具体用法?C++ UdpSocket怎么用?C++ UdpSocket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了UdpSocket类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: FD_ZERO

int SnmpRouted::setup(fd_set& set)
{
   FD_ZERO(&set);
   int maxfd = listener.getfd();
   FD_SET(maxfd, &set);
   for(int i = 0; i < MaxRequest; i++)
   {
      UdpSocket *dest = reqTable[i].dest;
      if(dest)
      {
         FD_SET(dest->getfd(), &set);
         if(i > maxfd) maxfd = i;
      }
   }

   return maxfd+1;
}
开发者ID:jortel,项目名称:libs,代码行数:17,代码来源:snmpRouted.cpp


示例2: main

int main()
{
    UdpSocket sock;
    char msg[100];
    int  msgLen;
    string reply="Server msg";
    struct sockaddr_in clientSockAddr;
    socklen_t sockLen;

    sock.initServer(5000);
    cout<<"Initialized the UDP server"<<endl;
    msgLen = sock.serverRecv(msg,sizeof(msg),&clientSockAddr,&sockLen);
    msg[msgLen] = 0;
    cout<<"Client reply:"<<endl;
    cout<<msg<<endl;
    sock.serverSend(reply.c_str(),reply.length(),&clientSockAddr,sizeof(clientSockAddr));
}
开发者ID:skupparu,项目名称:TcpSim,代码行数:17,代码来源:UdpSocketServer.cpp


示例3: serverUnreliable

// Test1: server unreliable message receive -----------------------------------
void serverUnreliable( UdpSocket &sock, const int max, int message[] ) {
  cerr << "server unreliable test:" << endl;

  // receive message[] max times
  for ( int i = 0; i < max; i++ ) {
    sock.recvFrom( ( char * ) message, MSGSIZE );   // udp message receive
    cerr << message[0] << endl;                     // print out message
  }
}
开发者ID:blong43,项目名称:css432,代码行数:10,代码来源:hw3a.cpp


示例4: Execute

        static typename T::VALUE_TYPE Execute(const typename T::VALUE_TYPE& value)
        {
            UdpSocket socket;
            socket.bind(0, 0);

            TestUdpSenderRunnable<T> testSender(socket.getSocketAddrInfo().port, value);
            Thread thread;
            thread.start(testSender);

            UdpSocketInputStream<1450> inStream(socket);

            typename T::VALUE_TYPE resultValue;
            inStream >> resultValue;

            thread.join();

            return resultValue;
        }
开发者ID:markusbischof,项目名称:capu,代码行数:18,代码来源:UdpSocketInputStreamTest.cpp


示例5: my_send

int my_send()
{
    printf("==== Send\n");

    char * msg = "hello";
    UdpSocket sender;
    DataBuffer buffer(1024);
    buffer.set_data_size(1024);
    buffer.set_data((YETI_Byte *)msg, strlen(msg));
    IpAddress address;
    address.resolve_name("localhost");
    SocketAddress socket_address(address, 9123);
    YETI_Result result = sender.send(buffer, &socket_address);
    if (YETI_FAILED(result)) {
        fprintf(stderr, "send() failed (%d)\n", result);
        return result;
    }
    return 0;
}
开发者ID:xindawndev,项目名称:cxl-yeti,代码行数:19,代码来源:YetiUdpTest.cpp


示例6: clientUnreliable

// Test 1: client unreliable message send -------------------------------------
void clientUnreliable( UdpSocket &sock, const int max, int message[] ) {
  cerr << "client: unreliable test:" << endl;

  // transfer message[] max times
  for ( int i = 0; i < max; i++ ) {
    message[0] = i;                            // message[0] has a sequence #
    sock.sendTo( ( char * )message, MSGSIZE ); // udp message send
    cerr << "message = " << message[0] << endl;
  }
}
开发者ID:blong43,项目名称:css432,代码行数:11,代码来源:hw3a.cpp


示例7: serverEarlyRetrans

void serverEarlyRetrans(UdpSocket &sock, const int max, int message[], 
						int windowSize) {
	cerr << "Server early retrans test:" << endl;

	int ack;				// Holds the acknowledgment
	bool serverArray[max];	// Holds messages that server needs from client
	int sequence = 0;		// The sequence # counter

	// Initialize all values in serverArray to false
	for (int i = 0; i < max; i++)
		serverArray[i] = false;

	while (sequence < max) {
		// Read the message from the client
		sock.recvFrom((char *)message, MSGSIZE);
		
		// Got needed message from client
		if (message[0] == sequence) {
			// Set the serverArray at sequence
			serverArray[sequence] = true;
			
			// Find the lowest number the server needs
			while (sequence < max) {
				if (serverArray[sequence] == false) {
					break;
				}
				sequence++;
			}
			
			// Send an ACK for previous seq #
			ack = sequence - 1;
		} 
		else {
			// Set the serverArray at message
			serverArray[message[0]] = true;
			
			// Send the number that is still needed 
			ack = sequence;
		}
		// Send the acknowledgment
		sock.ackTo((char *)&ack, sizeof(ack));
	}
}
开发者ID:blong43,项目名称:css432,代码行数:43,代码来源:udp.cpp


示例8: serverReliable

void serverReliable( UdpSocket &sock, const int max, int message[] ) {
	cerr << "server reliable test:" << endl;

	// receive message[] max times
	for ( int i = 0; i < max; ) {
		sock.recvFrom( ( char * ) message, MSGSIZE );   // udp message receive

		if ( message[0] >= max ) {
			cerr << "ERROR: " << message[0] << " is larger than max\n";
			break;
		}

		// Drops the message[] if its a duplicate
		if ( message[0] == i ) {
			sock.ackTo( ( char * ) message, MSGSIZE);		// send ACK to client
			//cerr << " ACKed: " << message[0] << endl; 
			i++;
		}
	}
}
开发者ID:blong43,项目名称:css432,代码行数:20,代码来源:udp.cpp


示例9: sizeof

/*
 * obj UdpSocket类型的指针
 */
void *UdpSocket::_runRecving(void* obj) {
    UdpSocket *udpSocket = (UdpSocket *)obj;
    
    struct sockaddr_in addr;
    socklen_t addrLen = sizeof(struct sockaddr_in);
    int errorNum;
    char data[MAX_BUF_SIZE];

    while (udpSocket->m_running) {
        bzero(&addr, sizeof(struct sockaddr_in));
        if((errorNum = recvfrom(udpSocket->m_socket, data, 
                    MAX_BUF_SIZE, 0,
                    (struct sockaddr*)&addr, &addrLen)) < 0) {
            printf("error num %d\n", errorNum);
            continue;
        }
        data[errorNum] = '\0';
        udpSocket->recvHandler(&addr, data);
    }
    return((void*)0);
}
开发者ID:lhc180,项目名称:Codes,代码行数:24,代码来源:UdpSocket.cpp


示例10: Main

	void UdpSendThread::Main() {
		SocketThreadOperation *op = mSocketThreadOperation;
		UdpSocket *s = (UdpSocket*)op->mSocket;
		ErrorType error;
		StopWatch sw;
		sw.Start();
		while (!ShouldEnd()) {
			error = s->Send(op->mIPAddress, op->mByteStream, Math::ClampLong(
				op->mTimeoutMS - sw.GetElapsedMilliseconds(), 0L, 16L));
			if (0L == op->mTimeoutMS ||
				(error && kErrorTimedOut != error) ||
				(0L < op->mTimeoutMS &&
				sw.GetElapsedMilliseconds() >= op->mTimeoutMS))
			{
				if (error)
					Error::Throw(error, String("[%s(%p, %p)]",
						FastFunctionName, this, op));
				s->OnSend(op->mID, op->mIPAddress, error);
				break;
			}
		}
	}
开发者ID:JSandrew4,项目名称:FastGdk,代码行数:22,代码来源:Network.cpp


示例11: main

int main(int argc, char* argv[])
{
	/*      Concept:

			 1) UdpSocket listens for input data.
			 2) Data is passed to H264Decoder which than parses
				the NALU files and passes everything to ffmpeg.
				The decoded data is than passed to the SdlViewer instance;
			 3) The SdlViewer uses SDL with OpenGL acceleration to show the received frames.
	 */
	
	for(int i = 1; i < argc; ++i) {
		std::string value(argv[i]);
		if (value == "--fullscreen") {
			fullscreen = true;
		}else if(value == "--oculus"){
			viewer = new OculusViewer(DEFAULT_WIDTH, DEFAULT_HEIGHT);
		}else if (value == "--help" || value == "-h") {
			cout << "--help           no idea what exactly this parameter does" << endl
				 << "--fullscreen     open fullscreen opengl context instead of vga window" << endl
				 << "--oculus   adjust screen window for Oculus Rift DK2" << endl;
			return 0;
		}
	}
	if(viewer == nullptr){
		viewer = new SdlViewer(DEFAULT_WIDTH, DEFAULT_HEIGHT);
	}

	input.initClient(cfg.getValueOfKey<string>("TARGET_IP").c_str(), TARGET_PORT);
	input.setInitCallback(&init);
	input.send(PROTOCOL_TYPE_INIT, nullptr, 0);
	viewer->setInputCallback(&inputCallback);
	viewer->setPositionCallback(&positionCallback);
	viewer->show(fullscreen);
	input.send(PROTOCOL_TYPE_CLOSE, nullptr, 0);
	input.close();

	return 0;
}
开发者ID:mustafatok,项目名称:idp_client,代码行数:39,代码来源:main.cpp


示例12: UdpSocket

void SnmpRouted::routeRequest()
{
   try
   {
      Request req;
      req.dest = new UdpSocket(destAddr);
      req.expTime = time(0)+RequestTimeout;
      if(req.dest)
      {
         req.dest->connect();
         int nbytes = listener.bytesToRead(sizeof(dataGram));
         listener.read(dataGram, nbytes);
         req.origAddr = listener.getSender();
         req.dest->write(dataGram, nbytes);
         int fd = req.dest->getfd();
         reqTable[fd] = req;
      }
   }
   catch(NetErr& e)
   {
      syslog(LOG_ERR, "Request not routed: %s", e.errm);
   }
}
开发者ID:jortel,项目名称:libs,代码行数:23,代码来源:snmpRouted.cpp


示例13: clientStopWait

int clientStopWait( UdpSocket &sock, const int max, int message[] ) {
	cerr << "Stop-and-wait test:" << endl;
	Timer t;
	int retransmits = 0;
	for ( int i = 0; i < max; i++ ) {					// transfer message[] max times
		message[0] = i;                            		// message[0] has a sequence #
		sock.sendTo((char*) message, MSGSIZE);			// send message
		t.start();										// start timer
		long lap;
		while ((lap = t.lap()) < 1500) {
			if(sock.pollRecvFrom() > 0) {				// if ack received before timer ends
				sock.recvFrom((char*)message, MSGSIZE);
				break;
			}
		}
		if (lap >= 1500) {								// timeout, so retransmit
			i--;
			retransmits++;
			cerr << retransmits << endl;
		}
	}
	return retransmits;
}
开发者ID:jahennen,项目名称:CSS_432,代码行数:23,代码来源:udp.cpp


示例14: serverEarlyRetrans

void serverEarlyRetrans( UdpSocket &sock, const int max, int message[], int windowSize ) {
	cerr << "server sliding window:" << endl;
	int seq = 0;
	int lastSeq = -1;
	int windowLoc = 0;
	vector<int> window(windowSize);
	for(int i = 0; i < windowSize; i++) { 				//init window
		window[i] = -1;
	}
	while(seq < max) {
		while( sock.pollRecvFrom() <=0 ){}				// pause until message
		sock.recvFrom( ( char * ) message, MSGSIZE );   	// udp message receive
		seq = *message;										// get the seq # from beginning of msg
		int index = seq % windowSize;
		if (index < windowLoc || index >= windowSize) { // seq is outside window
			ackPkt(lastSeq, sock);							// ack last contiguous packet.
			continue;										// drop packet
		} else if(index == windowLoc) {					// seq is next contiguous packet
			window[index] = seq;							// store seq in 1st slot
			lastSeq = seq;
			while(window[windowLoc] > -1) {					// while contiguous
				lastSeq = window[windowLoc];				// store value in lastSeq
				window[windowLoc] = -1;						// clean up value to -1
				windowLoc++;								// increment window
				windowLoc = windowLoc % windowSize;			// mod window if needed
				if (window[windowLoc] == -1) {				// if next slot is empty
					ackPkt(lastSeq, sock);					// ack last contiguous packet
				}
			}
		} else {										// seq is within window, so store
			window[index] = seq;							// store seq in correct slot
			ackPkt(lastSeq, sock);							// ack last contiguous packet
		}
		if (seq == max-1)
			break;
	}
}
开发者ID:jahennen,项目名称:CSS_432,代码行数:37,代码来源:udp.cpp


示例15: main

int main(){
	if(!winSockDll.Init()){
		std::cout<<"Couldn't load winsock"<<std::endl;
		system("pause");
		return 1;
	}
	connections = (Address*)calloc(64, sizeof(Address));

	addr = Address("127.0.0.1", 2222);
	sConnect = UdpSocket();
	sConnect.Bind(addr);
	std::cout << "Server started..." << std::endl;

	char* buffer = new char[512];
	bool clientexist = false;
	while(true){
		clientexist = false;
		ZeroMemory(buffer, 512);
		sConnect.Receive(buffer, 512, &storeAddr);
		for(int i = 0; i < Counter; i++){
			if(storeAddr.Equals(connections[i])){
				std::cout << "Client["<<i<<"]: "<<buffer<<std::endl;
				clientexist = true;
			}
		}
		if(!clientexist){
			connections[Counter] = storeAddr;
			std::cout<<"New Client: "<<Counter<<std::endl;
			std::cout << "Client["<<Counter<<"]: "<< buffer << std::endl;
			Counter++;
		}
	}

	winSockDll.Cleanup();
	return 0;
}
开发者ID:stijncr,项目名称:PixelDelirium,代码行数:36,代码来源:Server.cpp


示例16: ExternalCommunicationsSender

    ExternalCommunicationsSender( UdpSocket& externalSocket,
			IpEndpointName remoteServerEndpoint,
			int localToRemotePort,
            const char *userName, const char *userPassword,
            const char *groupName, const char *groupPassword )
        : lastAliveSentTime_( 0 )
        , externalSocket_( externalSocket )
		, remoteServerEndpoint_( remoteServerEndpoint )
		, localToServerEndpoint_( 
				externalSocket.LocalEndpointFor( remoteServerEndpoint ).address, 
				localToRemotePort )
        , userName_( userName )
        , userPassword_( userPassword )
        , groupName_( groupName )
        , groupPassword_( groupPassword )
    {
        PrepareAliveBuffer();
        PreparePingBuffer();
    }
开发者ID:gabrield,项目名称:beebox,代码行数:19,代码来源:OscGroupClient.cpp


示例17: main

int main()
{
    UdpSocket s;
    Host h("localhost", 2001);

    if (s.sendString("hello world", h) == AbstractSocket::Done)
        cout << "Done" << endl;

    else
        perror("Error");

    if (s.sendInt32(666, h) == AbstractSocket::Done)
        cout << "Done" << endl;

    else
        perror("Error");

    if (s.sendInt8('&', h) == AbstractSocket::Done)
        cout << "Done" << endl;

    else
        perror("Error");

    size_t ts = 21;

    if (s.sendCharArray("this is a char array", ts, h) == AbstractSocket::Done)
        cout << "Done" << endl;

    else
        perror("Error");

    Frame f;
    f << "This is a frame " << 666 << '\n';

    if (s.sendFrame(f, h) != AbstractSocket::Done)
        perror("error");

    else
        cout << "done" << endl;

    s.close();
}
开发者ID:AnXi-TieGuanYin-Tea,项目名称:CPPWrappers,代码行数:42,代码来源:Client.cpp


示例18: RemoveSocket

otError Udp::RemoveSocket(UdpSocket &aSocket)
{
    if (mSockets == &aSocket)
    {
        mSockets = mSockets->GetNext();
    }
    else
    {
        for (UdpSocket *socket = mSockets; socket; socket = socket->GetNext())
        {
            if (socket->GetNext() == &aSocket)
            {
                socket->SetNext(aSocket.GetNext());
                break;
            }
        }
    }

    aSocket.SetNext(NULL);

    return OT_ERROR_NONE;
}
开发者ID:lanyuwen,项目名称:openthread,代码行数:22,代码来源:udp6.cpp


示例19: _UdpSocket_GetMaxMsgSize

value _UdpSocket_GetMaxMsgSize(value a) {
	UdpSocket* s = (UdpSocket*) val_data(a);
	return alloc_int(s->GetMaxMsgSize());
}
开发者ID:datee,项目名称:hxudp,代码行数:4,代码来源:api.cpp


示例20: VerifyOrExit

otError Udp::HandleMessage(Message &aMessage, MessageInfo &aMessageInfo)
{
    otError error = OT_ERROR_NONE;
    UdpHeader udpHeader;
    uint16_t payloadLength;
    uint16_t checksum;

    payloadLength = aMessage.GetLength() - aMessage.GetOffset();

    // check length
    VerifyOrExit(payloadLength >= sizeof(UdpHeader), error = OT_ERROR_PARSE);

    // verify checksum
    checksum = Ip6::ComputePseudoheaderChecksum(aMessageInfo.GetPeerAddr(), aMessageInfo.GetSockAddr(),
                                                payloadLength, kProtoUdp);
    checksum = aMessage.UpdateChecksum(checksum, aMessage.GetOffset(), payloadLength);

#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
    VerifyOrExit(checksum == 0xffff, error = OT_ERROR_DROP);
#endif

    VerifyOrExit(aMessage.Read(aMessage.GetOffset(), sizeof(udpHeader), &udpHeader) == sizeof(udpHeader),
                 error = OT_ERROR_PARSE);
    aMessage.MoveOffset(sizeof(udpHeader));
    aMessageInfo.mPeerPort = udpHeader.GetSourcePort();
    aMessageInfo.mSockPort = udpHeader.GetDestinationPort();

    // find socket
    for (UdpSocket *socket = mSockets; socket; socket = socket->GetNext())
    {
        if (socket->GetSockName().mPort != udpHeader.GetDestinationPort())
        {
            continue;
        }

        if (socket->GetSockName().mScopeId != 0 &&
            socket->GetSockName().mScopeId != aMessageInfo.mInterfaceId)
        {
            continue;
        }

        if (!aMessageInfo.GetSockAddr().IsMulticast() &&
            !socket->GetSockName().GetAddress().IsUnspecified() &&
            socket->GetSockName().GetAddress() != aMessageInfo.GetSockAddr())
        {
            continue;
        }

        // verify source if connected socket
        if (socket->GetPeerName().mPort != 0)
        {
            if (socket->GetPeerName().mPort != udpHeader.GetSourcePort())
            {
                continue;
            }

            if (!socket->GetPeerName().GetAddress().IsUnspecified() &&
                socket->GetPeerName().GetAddress() != aMessageInfo.GetPeerAddr())
            {
                continue;
            }
        }

        socket->HandleUdpReceive(aMessage, aMessageInfo);
    }

exit:
    return error;
}
开发者ID:lanyuwen,项目名称:openthread,代码行数:69,代码来源:udp6.cpp



注:本文中的UdpSocket类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ Ufo类代码示例发布时间:2022-05-31
下一篇:
C++ UdpServer类代码示例发布时间:2022-05-31
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap