void TCPSOCKET_RECV_100K() { TCPSocket sock; _tcpsocket_connect_to_chargen_srv(sock); Timer timer; timer.start(); rcv_n_chk_against_rfc864_pattern(sock); timer.stop(); TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.close()); printf("MBED: Time taken: %fs\n", timer.read()); }
void TCPSOCKET_OPEN_CLOSE_REPEAT() { SKIP_IF_TCP_UNSUPPORTED(); TCPSocket *sock = new TCPSocket; if (!sock) { TEST_FAIL(); } for (int i = 0; i < 2; i++) { TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock->open(NetworkInterface::get_default_instance())); TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock->close()); } delete sock; }
void TCPSocket::accept(TCPSocket &client) { struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; socklen_t len = sizeof(addr); int s = ::accept(_sock, (struct sockaddr *)&addr, &len); if (s == -1) throw_net(("accept")); client.close(); client._sock = s; client._addr.ip = addr.sin_addr.s_addr; client._addr.port = ntohs(addr.sin_port); //real port }
void TCPSOCKET_RECV_100K_NONBLOCK() { TCPSocket sock; _tcpsocket_connect_to_chargen_srv(sock); sock.set_blocking(false); sock.sigio(callback(_sigio_handler, Thread::gettid())); Timer timer; timer.start(); rcv_n_chk_against_rfc864_pattern_nonblock(sock); timer.stop(); TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.close()); printf("MBED: Time taken: %fs\n", timer.read()); }
void TCPSOCKET_RECV_100K_NONBLOCK() { TCPSocket sock; nsapi_error_t err = _tcpsocket_connect_to_chargen_srv(sock); if (err != NSAPI_ERROR_OK) { TEST_FAIL(); return; } sock.set_blocking(false); sock.sigio(callback(_sigio_handler, Thread::gettid())); rcv_n_chk_against_rfc864_pattern_nonblock(sock); TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.close()); }
void runClient(const char * host, int port, const char * message) { printf("Setting up a client socket to %s:%d\n", host, port); TCPSocket socket; int err = socket.open(host, port); if(err) { const int msgSize = 128; char msgBuf[msgSize] = ""; printf("%s cannot open client socket to %s:%d -> %s\n", appname, host, port, strerror_s(msgBuf, msgSize, err)); return; } socket.setNoDelay(true); char buf[1024]; for(int i = 0; i < iterations; i++) { puts("Sending message"); sprintf(buf, "%s %d", message, i + 1); int32_t len = strlen(buf) + 1; socket.write( & len, 4); socket.write(buf, len); if(withreplies) { len = 0; socket.read( & len, 4); bzero(buf, sizeof(buf)); socket.read(buf, len); printf("Received reply \"%s\"\n", buf); } } puts("Closing"); socket.close(); }
/** * Test TCP data exchange via the asynchronous sigio() mechanism */ void test_tcp_echo_async() { TCPSocket sock; SocketAddress host_address; bool callback_triggered = false; int x; int size; driver.disconnect(); TEST_ASSERT(do_connect(&driver) == 0); TEST_ASSERT( driver.gethostbyname(MBED_CONF_APP_ECHO_SERVER, &host_address) == 0); host_address.set_port(MBED_CONF_APP_ECHO_TCP_PORT); tr_debug("TCP: Server %s address: %s on port %d.", MBED_CONF_APP_ECHO_SERVER, host_address.get_ip_address(), host_address.get_port()); TEST_ASSERT(sock.open(&driver) == 0) // Set up the async callback and set the timeout to zero sock.sigio(callback(async_cb, &callback_triggered)); sock.set_timeout(0); TEST_ASSERT(sock.connect(host_address) == 0); // Test min, max, and some random sizes in-between do_tcp_echo_async(&sock, 1, &callback_triggered); do_tcp_echo_async(&sock, MBED_CONF_APP_TCP_MAX_PACKET_SIZE, &callback_triggered); sock.close(); drop_connection(&driver); tr_debug("TCP packets of size up to %d byte(s) echoed asynchronously and successfully.", MBED_CONF_APP_TCP_MAX_PACKET_SIZE); }
int main() { #ifdef OS_WIN32 WSAData wsaData; int nCode; assert( WSAStartup(MAKEWORD(2, 2), &wsaData) == 0); #endif int sock = socket(AF_INET, SOCK_STREAM, 0); TCPServerSocket server (sock); TCPSocketAddress localAddr("127.0.0.1", 10001); if (server.bind(&localAddr)) { std::cout << server.getLastError().getErrorString() << std::endl; return -1; } if (server.listen(10)) { perror("While listening"); return -2; } TCPSocketAddress *addr = 0; server.poll(IODevice::POLL_READ,-1); TCPSocket *socket = (TCPSocket *)(server.accept((SocketAddress **)&addr)); if (socket == NULL) { std::cout << server.getLastError() << std::endl; return -3; } std::cout << "Get remote "<<socket->getPeerAddress()->getReadable()<<std::endl; socket->close(); server.close(); return 0; }
void ConnectThread::run() { QHostInfo addr = QHostInfo::fromName(mAddress); if (addr.error() != QHostInfo::NoError) { Q_EMIT error(addr.errorString()); return; } QHostAddress actualAddr; QList<QHostAddress> addresses = addr.addresses(); for (QList<QHostAddress>::const_iterator iter = addresses.begin(); iter != addresses.end(); ++ iter) { if (iter->protocol() == QAbstractSocket::IPv4Protocol) { actualAddr = *iter; break; } } if (actualAddr.isNull()) { Q_EMIT error(tr("无法解析域名: 找不到'%1'的IPv4地址").arg(mAddress)); return; } // Begin connection { std::string addr = actualAddr.toString().toStdString(); TCPSocketAddress remote (addr,mPort); IOVideoSource *src = 0; Error rc; TCPSocket *ctrl = new TCPSocket (::socket(AF_INET, SOCK_STREAM, 0)); TCPSocket *data = new TCPSocket (::socket(AF_INET, SOCK_STREAM, 0)); ctrl->setBlockingMode(false); data->setBlockingMode(false); ctrl->connect(&remote); do { rc = ctrl->poll(IODevice::POLL_WRITE,200); if (rc.isSuccess()) break; else if (rc.getErrorType() == Error::ERR_TIMEOUT) continue; else { rc.setErrorString("无法连接到远端服务器"); goto connect_ctrl_failed; } }while(!mShouldStop); data->connect(&remote); do { rc = data->poll(IODevice::POLL_WRITE,200); if (rc.isSuccess()) break; else if (rc.getErrorType() == Error::ERR_TIMEOUT) continue; else { rc.setErrorString("无法连接到远端服务器"); goto connect_data_failed; } }while(!mShouldStop); ctrl->setBlockingMode(true); data->setBlockingMode(true); src = new IOVideoSource(ctrl,data); rc = src->init(); if (rc.isError()) { rc.setErrorString("初始化视频源失败,原因为:" + rc.getErrorString()); goto init_video_source_failed; } mVideoSource = src; Q_EMIT success(); return; init_video_source_failed: delete src; connect_data_failed: connect_ctrl_failed: ctrl->close(); data->close(); delete ctrl; delete data; Q_EMIT error(QString::fromStdString(rc.getErrorString())); } }
// -------------------------------------------------------------------------- // ARDrone::getConfig() // Description : Get current configurations of AR.Drone. // Return value : SUCCESS: 1 FAILURE: 0 // -------------------------------------------------------------------------- int ARDrone::getConfig(void) { // Open the IP address and port TCPSocket sockConfig; if (!sockConfig.open(ip, ARDRONE_CONFIG_PORT)) { CVDRONE_ERROR("TCPSocket::open(port=%d) failed. (%s, %d)\n", ARDRONE_CONFIG_PORT, __FILE__, __LINE__); return 0; } // Send requests UDPSocket tmpCommand; tmpCommand.open(ip, ARDRONE_COMMAND_PORT); tmpCommand.sendf("AT*CTRL=%d,5,0\r", seq++); tmpCommand.sendf("AT*CTRL=%d,4,0\r", seq++); msleep(500); tmpCommand.close(); // Receive data char buf[4096] = {'\0'}; int size = sockConfig.receive((void*)&buf, sizeof(buf)); // Received something if (size > 0) { // Clear config struct memset(&config, 0, sizeof(ARDRONE_CONFIG)); // Parsing configurations char *token = strtok(buf, "\n"); if (token != NULL) parse(token, &config); while (token != NULL) { token = strtok(NULL, "\n"); if (token != NULL) parse(token, &config); } } #if 0 // For debug printf("general.num_version_config = %d\n", config.general.num_version_config); printf("general.num_version_mb = %d\n", config.general.num_version_mb); printf("general.num_version_soft = %s\n", config.general.num_version_soft); printf("general.drone_serial = %s\n", config.general.drone_serial); printf("general:soft_build_date = %s\n", config.general.soft_build_date); printf("general:motor1_soft = %f\n", config.general.motor1_soft); printf("general:motor1_hard = %f\n", config.general.motor1_hard); printf("general:motor1_supplier = %f\n", config.general.motor1_supplier); printf("general:motor2_soft = %f\n", config.general.motor2_soft); printf("general:motor2_hard = %f\n", config.general.motor2_hard); printf("general:motor2_supplier = %f\n", config.general.motor2_supplier); printf("general:motor3_soft = %f\n", config.general.motor3_soft); printf("general:motor3_hard = %f\n", config.general.motor3_hard); printf("general:motor3_supplier = %f\n", config.general.motor3_supplier); printf("general:motor4_soft = %f\n", config.general.motor4_soft); printf("general:motor4_hard = %f\n", config.general.motor4_hard); printf("general:motor4_supplier = %f\n", config.general.motor4_supplier); printf("general.ardrone_name = %s\n", config.general.ardrone_name); printf("general.flying_time = %d\n", config.general.flying_time); printf("general.navdata_demo = %s\n", config.general.navdata_demo ? "true" : "false"); printf("general.com_watchdog = %d\n", config.general.com_watchdog); printf("general.video_enable = %s\n", config.general.video_enable ? "true" : "false"); printf("general.vision_enable = %s\n", config.general.vision_enable ? "true" : "false"); printf("general.vbat_min = %d\n", config.general.vbat_min); printf("general.localtime = %d\n", config.general.localtime); printf("general.navdata_options = %d\n", config.general.navdata_options); printf("control:accs_offset = {%f, %f, %f}\n", config.control.accs_offset[0], config.control.accs_offset[1], config.control.accs_offset[2]); printf("control:accs_gains = { %f %f %f %f %f %f %f %f %f }\n", config.control.accs_gains[0], config.control.accs_gains[1], config.control.accs_gains[2], config.control.accs_gains[3], config.control.accs_gains[4], config.control.accs_gains[5], config.control.accs_gains[6], config.control.accs_gains[7], config.control.accs_gains[8]); printf("control:gyros_offset = { %f %f %f }\n", config.control.gyros_offset[0], config.control.gyros_offset[1], config.control.gyros_offset[2]); printf("control:gyros_gains = { %f %f %f }\n", config.control.gyros_gains[0], config.control.gyros_gains[1], config.control.gyros_gains[2]); printf("control:gyros110_offset = { %f %f }\n", config.control.gyros110_offset[0], config.control.gyros110_offset[1]); printf("control:gyros110_gains = { %f %f }\n", config.control.gyros110_gains[0], config.control.gyros110_gains[1]); printf("control:magneto_offset = { %f %f %f }\n", config.control.magneto_offset[0], config.control.magneto_offset[1], config.control.magneto_offset[2]); printf("control:magneto_radius = %f\n", config.control.magneto_radius); printf("control:gyro_offset_thr_x = %f\n", config.control.gyro_offset_thr_x); printf("control:gyro_offset_thr_y = %f\n", config.control.gyro_offset_thr_y); printf("control:gyro_offset_thr_z = %f\n", config.control.gyro_offset_thr_z); printf("control:pwm_ref_gyros = %d\n", config.control.pwm_ref_gyros); printf("control:osctun_value = %d\n", config.control.osctun_value); printf("control:osctun_test = %s\n", config.control.osctun_test ? "true" : "false"); printf("control:altitude_max = %d\n", config.control.altitude_max); printf("control:altitude_min = %d\n", config.control.altitude_min); printf("control:outdoor = %s\n", config.control.outdoor ? "true" : "false"); printf("control:flight_without_shell = %s\n", config.control.flight_without_shell ? "true" : "false"); printf("control:autonomous_flight = %s\n", config.control.autonomous_flight ? "true" : "false"); printf("control:flight_anim = %d,%d\n", config.control.flight_anim[0], config.control.flight_anim[1]); printf("control:control_level = %d\n", config.control.control_level); printf("control:euler_angle_max = %f\n", config.control.euler_angle_max); printf("control:control_iphone_tilt = %f\n", config.control.control_iphone_tilt); printf("control:control_vz_max = %f\n", config.control.control_vz_max); printf("control:control_yaw = %f\n", config.control.control_yaw); printf("control:manual_trim = %s\n", config.control.manual_trim ? "true" : "false"); printf("control:indoor_euler_angle_max = %f\n", config.control.indoor_euler_angle_max); printf("control:indoor_control_vz_max = %f\n", config.control.indoor_control_vz_max); printf("control:indoor_control_yaw = %f\n", config.control.indoor_control_yaw); printf("control:outdoor_euler_angle_max = %f\n", config.control.outdoor_euler_angle_max); printf("control:outdoor_control_vz_max = %f\n", config.control.outdoor_control_vz_max); printf("control:outdoor_control_yaw = %f\n", config.control.outdoor_control_yaw); printf("control:flying_mode = %d\n", config.control.flying_mode); printf("control:hovering_range = %d\n", config.control.hovering_range); printf("network:ssid_single_player = %s\n", config.network.ssid_single_player); printf("network:ssid_multi_player = %s\n", config.network.ssid_multi_player); printf("network:wifi_mode = %d\n", config.network.wifi_mode); printf("network:wifi_rate = %d\n", config.network.wifi_rate); printf("network:owner_mac = %s\n", config.network.owner_mac); printf("pic:ultrasound_freq = %d\n", config.pic.ultrasound_freq); printf("pic:ultrasound_watchdog = %d\n", config.pic.ultrasound_watchdog); printf("pic:pic_version = %d\n", config.pic.pic_version); printf("video:camif_fps = %d\n", config.video.camif_fps); printf("video:camif_buffers = %d\n", config.video.camif_buffers); printf("video:num_trackers = %d\n", config.video.num_trackers); printf("video:video_storage_space = %d\n", config.video.video_storage_space); printf("video:video_on_usb = %s\n", config.video.video_on_usb ? "true" : "false"); printf("video:video_file_index = %d\n", config.video.video_file_index); printf("video:bitrate = %d\n", config.video.bitrate); printf("video:bitrate_ctrl_mode = %d\n", config.video.bitrate_ctrl_mode); printf("video:bitrate_storage = %d\n", config.video.bitrate_storage); printf("video:codec_fps = %d\n", config.video.codec_fps); printf("video:video_codec = %d\n", config.video.video_codec); printf("video:video_slices = %d\n", config.video.video_slices); printf("video:video_live_socket = %d\n", config.video.video_live_socket); printf("video:max_bitrate = %d\n", config.video.max_bitrate); printf("video:video_channel = %d\n", config.video.video_channel); printf("leds:leds_anim = %d,%d,%d\n", config.leds.leds_anim[0], config.leds.leds_anim[1], config.leds.leds_anim[2]); printf("detect:enemy_colors = %d\n", config.detect.enemy_colors); printf("detect:enemy_without_shell = %d\n", config.detect.enemy_without_shell); printf("detect:groundstripe_colors = %d\n", config.detect.groundstripe_colors); printf("detect:detect_type = %d\n", config.detect.detect_type); printf("detect:detections_select_h = %d\n", config.detect.detections_select_h); printf("detect:detections_select_v_hsync = %d\n", config.detect.detections_select_v_hsync); printf("detect:detections_select_v = %d\n", config.detect.detections_select_v); printf("syslog:output = %d\n", config.syslog.output); printf("syslog:max_size = %d\n", config.syslog.max_size); printf("syslog:nb_files = %d\n", config.syslog.nb_files); printf("custom:application_desc = %s\n", config.custom.application_desc); printf("custom:profile_desc = %s\n", config.custom.profile_desc); printf("custom:session_desc = %s\n", config.custom.session_desc); printf("custom:application_id = %s\n", config.custom.application_id); printf("custom:profile_id = %s\n", config.custom.profile_id); printf("custom:session_id = %s\n", config.custom.session_id); printf("userbox:userbox_cmd = %d\n", config.userbox.userbox_cmd); printf("gps:latitude = %f\n", config.gps.latitude); printf("gps:longitude = %f\n", config.gps.longitude); printf("gps:altitude = %f\n", config.gps.altitude); #endif // Finalize sockConfig.close(); return 1; }
void Done() { gSocket.close(); cout << "closed connection to " << gHost << ":" << gPort << "\n"; }
TCPSocket* ModuleMap::getMapLoadingSocket( uint32 mapID, uint32 loadMapRequestType, const char* handshake, byte zoomlevel, MapSafeVector* loadedMaps, uint32* mapVersion, uint32* generatorVersion ) { uint32 mapVersionToUse = MAX_UINT32; uint32 generatorVersionToUse = MAX_UINT32; if ( mapVersion != NULL && generatorVersion != NULL ) { // Set the versions to use to the ones sent in mapVersionToUse = *mapVersion; generatorVersionToUse = *generatorVersion; // Set the ones sent in to MAX_UINT32 to detect errors *mapVersion = MAX_UINT32; *generatorVersion = MAX_UINT32; } DatagramReceiver receiver(8000, DatagramReceiver::FINDFREEPORT); mc2dbg4 << here << " localport " << receiver.getPort() << endl; uint32 mapip = MultiCastProperties::getNumericIP( MODULE_TYPE_MAP, true ); uint16 mapport = MultiCastProperties::getPort( MODULE_TYPE_MAP, true ); // check map set uint32 mapSet = Properties::getMapSet(); if (mapSet != MAX_UINT32) { // code also exists in PacketContainer.cpp, move to utility function? mc2dbg4 << "[ModuleMap] going to change IP and port due to mapSet being set. " "mapSet: " << mapSet << ", IP before: " << prettyPrintIP(mapip) << ", port before: " << mapport << endl; mapip = mapip + (mapSet << 8); mapport = mapport | (mapSet << 13); mc2dbg4 << "[ModuleMap] changed IP and port. IP now: " << prettyPrintIP(mapip) << ", port now: " << mapport << endl; } uint32 status = StringTable::NOT; int maxRetries = 10; int nbrRetries = 0; Packet _pack(65536); // For receiving the mapreply DatagramSender sock; const int originalwaittime = 2500000; // Wait 2.5 seconds. const int mapnotfoundwaittime = 2500000; // Wait 2.5 seconds. int waittime = originalwaittime; TCPSocket* TCPsock = NULL; while ( status != StringTable::OK && nbrRetries++ <= maxRetries ) { if ( nbrRetries > 1 ) { mc2log << info << here << " Retrying " << nbrRetries - 1 << " of " << maxRetries << endl; } if(loadedMaps != NULL) loadedMaps->jobThreadIsAlive(); // reset Jthread timeout clock. MapRequestPacket reqpack( uint16(1), // reqID uint16(1), // PacketID byte(loadMapRequestType), // Type of module mapID, // mapID zoomlevel, // Well, zoomlevel. mapVersionToUse, generatorVersionToUse ); reqpack.setOriginIP( NetUtility::getLocalIP() ); reqpack.setOriginPort( receiver.getPort() ); reqpack.setResendNbr((byte) nbrRetries-1); // Send request to open TCP connection between local and mapmodule if (!(sock.send(&reqpack, mapip, mapport))) { mc2log << error << here << " could not send - retrying" << endl; continue; // Go another round in the loop. } mc2dbg4 << "After send!" << endl; // Receive packet with ip and port to a mapModule if (!(receiver.receive(&_pack, waittime))) { mc2log << error << here << " error receiving ack - retrying" << endl; waittime = originalwaittime; continue; // Go another round in the loop. } bool timeout = false; while ( _pack.getSubType() == Packet::PACKETTYPE_ACKNOWLEDGE && ! timeout ) { AcknowledgeRequestReplyPacket* ackPack = static_cast<AcknowledgeRequestReplyPacket*>(&_pack); uint32 packtime = ((AcknowledgeRequestReplyPacket*)&_pack)->getETA() * 1000; mc2log << info << "Got ack with " << packtime << " us delay" << endl; if ( ackPack->getStatus() != StringTable::OK ) { return NULL; } timeout = !receiver.receive(&_pack, packtime); } if ( timeout ) { mc2log << error << "Got timeout after receiving ack-pack" << endl; continue; // Go around again } if ( _pack.getSubType() != Packet::PACKETTYPE_MAPREPLY ) { mc2log << error << "Got packet with subtype " << _pack.getSubTypeAsString() << " when expecting loadmapreply" << endl; continue; // Please try again. } MapReplyPacket* pack = (MapReplyPacket *)&_pack; status = pack->getStatus(); if ( status != StringTable::OK || pack->getMapID() != mapID ) { mc2log << warn << "Got status \"" << StringTable::getString( StringTable::stringCode(pack->getStatus()), StringTable::ENGLISH) << "\"-retrying. Wanted map = " << mapID << ", got reply for map = " << pack->getMapID() << endl; if ( status == StringTable::MAPNOTFOUND ) { // Wait longer if map not found ( loading? ) waittime = mapnotfoundwaittime; } if ( mapID != pack->getMapID() ) { status = StringTable::NOT; // Keep the loop running. } continue; // Go another round in the loop. } if ( mapVersion != NULL && generatorVersion != NULL ) { // Set the versions so that we know what we are caching. mc2dbg8 << "[ModuleMap]: Version from packet " << hex << pack->getMapVersion() << ":" << pack->getGeneratorVersion() << dec << endl; *mapVersion = pack->getMapVersion(); *generatorVersion = pack->getGeneratorVersion(); // Check if new map is needed. if ( ! pack->newMapNeeded(mapVersionToUse, generatorVersionToUse) ) { // Same version. Use the cached map. return NULL; } } TCPsock = new TCPSocket; mc2dbg4 << here << " opening socket" << endl; TCPsock->open(); uint32 ip = pack->getReplyIP(); uint16 port = pack->getReplyPort(); if ( ! TCPsock->connect(ip, port ) ) { mc2log << error << "Couldn't connect to " << ip << ":" << port << " - retrying" << endl; // Set status to not ok. status = StringTable::NOT; TCPsock->close(); delete TCPsock; TCPsock = NULL; continue; // Please try again. } // Handshaking mc2dbg4 << "Starting handshake" << endl; int length = strlen(handshake) + 1; if ( TCPsock->writeAll( (byte*)handshake, length ) != length ) { mc2log << error << here << " handshake failed " << endl; status = StringTable::NOT; TCPsock->close(); delete TCPsock; TCPsock = NULL; continue; // Please try again. } else { mc2dbg4 << "done" << endl; } } return TCPsock; // Should be NULL if we failed }