int main(int argc, char*argv[]){ if(argc < 4){ printf("use it right u dummie\n"); exit(1); } int srcPort = atoi(argv[1]); char* destIp = argv[2]; int destPort = atoi(argv[3]); UDPSocket* Socket = new UDPSocket(); Socket->Init(); Socket->Bind(srcPort); Socket->SetBlocking(false); Socket->On(0, function1); auto last = std::chrono::high_resolution_clock::now(); while(1){ auto now = std::chrono::high_resolution_clock::now(); auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now - last); if(ms.count() > 2000){ Socket->Send(0, "hello", sizeof("hello"), destIp, destPort); last = now; } Socket->PollEvents(); } }
void ExternalConnectThread::ThreadFunc() { m_udpSocket = m_address.m_socketFactory->CreateSocket(); UDPSocket* socket = dynamic_cast<UDPSocket*>(m_udpSocket); if(!socket || !socket->Bind(m_address.m_localIP, m_address.m_localPort)) { SignalError(); return; } socket->SetSendAddr(m_address.m_ip, m_address.m_port); std::string data = m_address.m_moduleName; int size = m_address.m_moduleName.size(); while(!IsStop()) { if(m_changeAddr.Wait(1000) == Semaphore::TIMEOUT) { if (!socket->Send((char*)&size, sizeof(size)) || !socket->Send((char*)data.c_str(), data.size() * sizeof(char))) { SignalError(); return; } } else { break; } } UDTSecureSocketFactory* udtSocketFactory = dynamic_cast<UDTSecureSocketFactory*>(m_address.m_socketFactory); if(!udtSocketFactory) { SignalError(); return; } udtSocketFactory->SetUdpSocket(socket->GetSocket()); m_csSocket.Enter(); m_udpSocket = 0; m_csSocket.Leave(); ConnectThread::ThreadFunc(); }
// Called every 10 ms...use for "resending" // Outputs: // TRUE if any instrument error has happened; FALSE otherwise bool Instrument::CachedPacket::Tick(const UDPSocket & rcUDP) { if (m_enSendMode == MT_WAITING_FOR_REPLY) { if (--m_nTickCount <= 0) // If time to resend { if (--m_nRetryCount > 0) // If not too many retries { TRACE("********************Resending packet******************* type: 0x%02X\n", ((cbPKT_GENERIC *)m_abyPacket)->type ); rcUDP.Send(m_abyPacket, m_cbPacketBytes); m_nTickCount = m_nMaxTickCount; } else { // true means that we have an error here return true; } } } return false; }
void Run() { const int port = 30003; UDPSocket socket; socket.Bind(port); const char sendbuffer[] = "hello world!"; socket.Send(Address(127,0,0,1,port), sendbuffer, sizeof(sendbuffer)); sleep_ms(50); char rcvbuffer[256]; memset(rcvbuffer, 0, sizeof(rcvbuffer)); Address sender; for(;;) { int bytes_read = socket.Receive(sender, rcvbuffer, sizeof(rcvbuffer)); if(bytes_read < 0) break; } //FIXME: This fails on some systems assert(strncmp(sendbuffer, rcvbuffer, sizeof(sendbuffer))==0); assert(sender.getAddress() == Address(127,0,0,1, 0).getAddress()); }