Example #1
0
int AbstractSocket::timeoutProcess(bool read/*=true*/)
{
	if (d->timeout == 0) return 0;

	struct timeval t;
	fd_set readfds;

 	t.tv_sec = d->timeout;
	t.tv_usec = d->timeoutUsec;

	FD_ZERO (&readfds);
	FD_SET (socketDescriptor(), &readfds);

	int n = 0;
	do {
		if (read)
			n = ::select (socketDescriptor() + 1, &readfds, 0, 0, &t);
		else
			n = ::select (socketDescriptor() + 1, 0, &readfds, 0, &t);
	} while  (n == -1 && errno == EINTR);

	if (n == -1) 
		return -1;
	if (n == 0) 
		return -2;

	return 0;
}
Example #2
0
bool AbstractSocket::bind()
{
	if (isClosed()) 
	{
		//printf("AbstractSocket::bind not opened socket\n");
		return false;
	}

	// Reuse Address
	if (d->socketType == TcpSocket)
	{
		int opt = 1;
#ifndef WIN32
		setsockopt(socketDescriptor(), SOL_SOCKET, SO_REUSEADDR, 
			&opt, sizeof(opt));
#else
		setsockopt(socketDescriptor(), SOL_SOCKET, SO_REUSEADDR, 
			 (const char *)&opt, sizeof(opt));
#endif
	}

	int retn = -1;
	if (d->socketType == UdsSocket)
	{
#ifndef WIN32
		sockaddr_un addr;
		memset(&addr, 0, sizeof(sockaddr_un));
		addr.sun_family = AF_UNIX;
		strcpy(addr.sun_path, "/tmp/.kosocket");

		retn = ::bind(socketDescriptor(), (sockaddr*)&addr, sizeof(addr));
#else
		// TODO:...
#endif
	}
	else
	{
		sockaddr_in addr;
		memset(&addr, 0, sizeof(sockaddr_in));
		addr.sin_family = AF_INET;
		addr.sin_addr.s_addr = htonl(INADDR_ANY);
		addr.sin_port = htons(port());

		retn = ::bind(socketDescriptor(), (sockaddr*)&addr, sizeof(addr));
	}

	if (retn == -1)
	{
		//printf("TcpSock::listen failed to bind\n");
		return false;
	}

	return true;
}
Example #3
0
void AbstractSocket::close()
{
	if (socketDescriptor() == -1) return;

#ifndef WIN32
	shutdown(socketDescriptor(), SHUT_RDWR);
	::close(socketDescriptor());
#else
	closesocket(socketDescriptor());
	//WSACleanup();
#endif
	setSocketDescriptor(-1);
}
Example #4
0
void APing::StartServer(const int listeningPort = 8888, const FString& responseString = "")
{
	server = RakNet::RakPeerInterface::GetInstance();
	int i = server->GetNumberOfAddresses();

	char* charString = TCHAR_TO_UTF8(*responseString);
	//char* charString = TCHAR_TO_UTF8((L""));
	UE_LOG(RakNet_Ping, Log, TEXT("Server response string length: %d"), strlen(charString));
	UE_LOG(RakNet_Ping, Log, TEXT("Server response string: %s"), *FString(UTF8_TO_TCHAR(charString)));
	//char* charString = TCHAR_TO_ANSI(L"abc123");
	//char enumData[512] = TCHAR_TO_ANSI(L"abc123中文字串あいうえお");
	//char enumData[512] = "abc123";
	server->SetOfflinePingResponse(charString, (const unsigned int)strlen(charString) + 1);

	// The server has to be started to respond to pings.
	RakNet::SocketDescriptor socketDescriptor(listeningPort, 0);
	bool b = server->Startup(2, &socketDescriptor, 1) == RakNet::RAKNET_STARTED;
	server->SetMaximumIncomingConnections(2);
	if (b)
	{
		UE_LOG(RakNet_Ping, Log, TEXT("Server started, waiting for connections."));
	}
	else
	{
		UE_LOG(RakNet_Ping, Error, TEXT("Server start failed!"));
	}
}
Example #5
0
void MyGameManager::OneTimeInit()
{
	m_bPlayingTheGame = false;

	// the game manager should listen to the following callbacks:
	Vision::Callbacks.OnEditorModeChanged += this;
	Vision::Callbacks.OnBeforeSceneLoaded += this;
	Vision::Callbacks.OnBeforeSceneUnloaded += this;
	Vision::Callbacks.OnAfterSceneLoaded += this;
	Vision::Callbacks.OnUpdateSceneBegin += this;
	Vision::Callbacks.OnWorldDeInit += this;
	Vision::Callbacks.OnFrameUpdatePreRender += this;

	// RAKNET

	if (client != NULL) return;

	// Pointers to the interfaces of our server and client.
	// Note we can easily have both in the same program
	client = RakNet::RakPeerInterface::GetInstance();

	RakNet::SystemAddress clientID = RakNet::UNASSIGNED_SYSTEM_ADDRESS;

	RakNet::SocketDescriptor socketDescriptor(0, 0);
	socketDescriptor.socketFamily = AF_INET;
	auto startResult = client->Startup(8, &socketDescriptor, 1);
	client->SetOccasionalPing(true);

	RakNet::ConnectionAttemptResult car = client->Connect("192.168.0.14", 1234, "Rumpelstiltskin", (int) strlen("Rumpelstiltskin"));
	RakAssert(car == RakNet::CONNECTION_ATTEMPT_STARTED);
}
bool CNetworkModule::Startup(void)
{
	// Create the socket descriptor
	RakNet::SocketDescriptor socketDescriptor(CVAR_GET_INTEGER("port"), CVAR_GET_STRING("hostaddress").Get());

	// Attempt to startup raknet
	bool bReturn = (m_pRakPeer->Startup(CVAR_GET_INTEGER("maxplayers"), &socketDescriptor, 1, 0) == RakNet::RAKNET_STARTED);

	// Did it start?
	if(bReturn)
	{
		// Set the maximum incoming connections
		m_pRakPeer->SetMaximumIncomingConnections(CVAR_GET_INTEGER("maxplayers"));

		// Get the password string
		CString strPassword = CVAR_GET_STRING("password");

		// Do we have a password?
		if(strPassword.GetLength() > 0)
		{
			// Set the server password
			m_pRakPeer->SetIncomingPassword(strPassword.Get(), strPassword.GetLength());
		}
	}

	// Return
	return bReturn;
}
Example #7
0
void Session::processRpcAnswer(QByteArray response) {
    qint32 len = response.length();

    qCDebug(TG_CORE_SESSION) << "connection #" << socketDescriptor() << "received rpc answer with" << len << "content bytes by session" << QString::number(m_sessionId, 16);

    InboundPkt p(response.data(), len);
    processRpcMessage(p);
}
Example #8
0
int AbstractSocket::bytesAvailable()
{
	int availBytes = 0;
#ifndef WIN32
	if (ioctl(socketDescriptor(),FIONREAD, &availBytes) != 0)
	{
		//printf("AbstractSocket::bytesAvailable errno:%d\n", errno);
		return -1;
	}
#else
	if (ioctlsocket(socketDescriptor(),FIONREAD, (u_long*)&availBytes) != 0)
	{
		return -1;
	}
#endif

	return availBytes;
}
bool PeerInformationSocket::init(const QString &name, const QString &state)
{
  if (m_timer)
    {
      m_timer->stop();
    }

  m_name = name;
  m_state = state;

  // XXX - close socket if already opened?

  // create multicast socket, bind to port
  if (!bind(CITP_PINF_MULTICAST_PORT, ShareAddress | ReuseAddressHint))
    {
      qDebug() << "Multicast bind failed";
      return false;
    }
  
  struct ip_mreq mreq;
  mreq.imr_multiaddr.s_addr = inet_addr(CITP_PINF_MULTICAST_IP);
  mreq.imr_interface.s_addr = INADDR_ANY;
  int r = ::setsockopt(socketDescriptor(), IPPROTO_IP, IP_ADD_MEMBERSHIP,
		       (const char *)&mreq, sizeof(struct ip_mreq));
  if (0 != r)
    {
      qDebug() << "setsockopt failed, r:" << r;
      return false;
    }


  delete m_packetBuffer;

  m_packetBuffer = PacketCreator::createPLocPacket(PacketCreator::LightingConsole, name, state, m_packetBufferLen);
  if (!m_packetBuffer)
    {
      m_packetBufferLen = 0;
      return false;
    }

  transmitPLoc();

  // XXX - don't connect this more than once..
  connect(this, SIGNAL(readyRead()),
  	  this, SLOT(handleReadReady()));

  
  if (m_timer)
    {
      m_timer->start();
    }
  

  return true;
}
void AbstractSocket::timerEvent(QTimerEvent * event) // TODO: each socket must self managed > done?
{
    Q_D(AbstractSocket);
    if (event->timerId() == d->expirationDelayTimerId)
    {
        log("AbstractSocket::timerEvent: expired");
        emit expired(socketDescriptor());
        return;
    }
    QSslSocket::timerEvent(event);
}
Example #11
0
bool CNetServer::Startup(unsigned short usPort, int iMaxPlayers, String strHostAddress)
{
	RakNet::SocketDescriptor socketDescriptor(usPort, strHostAddress.Get());
	// TODO: Return the real result instead of a boolean
	bool bStarted = (m_pRakPeer->Startup(iMaxPlayers, &socketDescriptor, 1, THREAD_PRIORITY_NORMAL) == RakNet::RAKNET_STARTED);

	if(bStarted)
		m_pRakPeer->SetMaximumIncomingConnections(iMaxPlayers);

	return bStarted;
}
Example #12
0
void cNetCode::Connect(char *ipaddress, char *port, char *clientport)
{
	RakNet::SocketDescriptor socketDescriptor(atoi(clientport), 0);

	socketDescriptor.socketFamily = AF_INET;
	cNetCode::client->Startup(8, &socketDescriptor, 1);
	cNetCode::client->SetOccasionalPing(true);

	RakNet::ConnectionAttemptResult car = cNetCode::client->Connect(ipaddress, atoi(port), "fivemp_dev", (int)strlen("fivemp_dev"));
	RakAssert(car == RakNet::CONNECTION_ATTEMPT_STARTED);
}
Example #13
0
	bool NetListener::startListen (int port)
	{
		pPeer->SetTimeoutTime(5000,RakNet::UNASSIGNED_SYSTEM_ADDRESS);
		RakNet::SocketDescriptor socketDescriptor(port,0);
		socketDescriptor.socketFamily=AF_INET;
		pPeer->SetMaximumIncomingConnections(MAX_CONNECTION);
		RakNet::StartupResult sr;
		sr=pPeer->Startup(MAX_CONNECTION, &socketDescriptor, 1);

		return sr == RakNet::RAKNET_STARTED ;
	}
Example #14
0
bool TetrisClient::Init()
{
	RakNet::RakNetStatistics *rss;
	// Pointers to the interfaces of our server and client.
	// Note we can easily have both in the same program
	m_interface = RakNet::RakPeerInterface::GetInstance();
	//	m_interface->InitializeSecurity(0,0,0,0);
	//RakNet::PacketLogger packetLogger;
	//m_interface->AttachPlugin(&packetLogger);

	// GetPacketIdentifier returns this
	unsigned char packetIdentifier;

	// Just so we can remember where the packet came from
	bool isServer;

	// Record the first client that connects to us so we can pass it to the ping function
	m_clientID = RakNet::UNASSIGNED_SYSTEM_ADDRESS;

	// Crude interface

	// Holds user data
	char ip[64], serverPort[30], clientPort[30];

	printf("This is a sample implementation of a text based chat client.\n");
	printf("Connect to the project 'Chat Example Server'.\n");
	printf("Difficulty: Beginner\n\n");

	// Get our input
	strcpy(clientPort, "5");
	strcpy(ip, "127.0.0.1");
	strcpy(serverPort, "1234");

	// Connecting the client is very simple.  0 means we don't care about
	// a connectionValidationInteger, and false for low priority threads
	RakNet::SocketDescriptor socketDescriptor(atoi(clientPort), 0);
	socketDescriptor.socketFamily = AF_INET;
	m_interface->Startup(8, &socketDescriptor, 1);
	m_interface->SetOccasionalPing(true);

	RakNet::ConnectionAttemptResult car = m_interface->Connect(ip, atoi(serverPort), "Rumpelstiltskin", (int)strlen("Rumpelstiltskin"));
	RakAssert(car == RakNet::CONNECTION_ATTEMPT_STARTED);

	printf("\nMy IP addresses:\n");
	unsigned int i;
	for (i = 0; i < m_interface->GetNumberOfAddresses(); i++)
	{
		printf("%i. %s\n", i + 1, m_interface->GetLocalIP(i));
	}

	printf("My GUID is %s\n", m_interface->GetGuidFromSystemAddress(RakNet::UNASSIGNED_SYSTEM_ADDRESS).ToString());

	return true;
}
Example #15
0
void APing::ClientPing(const FString& host = "127.0.0.1", const int port = 8888)
{
	UE_LOG(RakNet_Ping, Log, TEXT("APing::ClientPing"));

	client = RakNet::RakPeerInterface::GetInstance();
	RakNet::SocketDescriptor socketDescriptor(0, 0);
	client->Startup(1, &socketDescriptor, 1);
	client->Ping(TCHAR_TO_ANSI(*host), port, false);

	//waitReceivedData = true;

}
Example #16
0
/*!
    Returns the security options currently active for the socket.

    \sa isAuthenticated(), isEncrypted()
 */
QBluetooth::SecurityOptions QBluetoothL2CapSocket::securityOptions() const
{
    if (state() == QBluetoothL2CapSocket::UnconnectedState)
        return 0;

    QBluetooth::SecurityOptions options;

    if (_q_getL2CapSecurityOptions(socketDescriptor(), options))
        return options;

    return 0;
}
Example #17
0
    void ServerClient::regenerate() {
        if(m_server)
            destroy();
        m_server = RakNet::RakPeerInterface::GetInstance();
        
        // Connecting the client is very simple.  0 means we don't care about
        // a connectionValidationInteger, and false for low priority threads
        RakNet::SocketDescriptor socketDescriptor(0,0);
        socketDescriptor.socketFamily=AF_INET;
        m_server->Startup(8,&socketDescriptor, 1);
        m_server->SetOccasionalPing(true);
		m_server->SetTimeoutTime(10000,RakNet::UNASSIGNED_SYSTEM_ADDRESS);
        onDisconnect();
    }
Example #18
0
bool RakNetTransport::Start(unsigned short port, bool serverMode)
{
	AutoAllocate();
	rakPeer->InitializeSecurity(0,0,0,0);

	if (serverMode)
	{
		// Allow up to 8 remote systems to login
		rakPeer->SetMaximumIncomingConnections(8);
	}

	SocketDescriptor socketDescriptor(port,0);
	return rakPeer->Startup(8, 250, &socketDescriptor, 1);
}
Example #19
0
void main(void)
{
	peer1=RakNetworkFactory::GetRakPeerInterface();
	peer2=RakNetworkFactory::GetRakPeerInterface();
	peer1->SetMaximumIncomingConnections(1);
	peer2->SetMaximumIncomingConnections(1);
	SocketDescriptor socketDescriptor(1234,0);
	peer1->Startup(1,0,&socketDescriptor, 1);
	socketDescriptor.port=1235;
	peer2->Startup(1,0,&socketDescriptor, 1);
	peer1->Connect("127.0.0.1", 1235, 0, 0);
	peer2->Connect("127.0.0.1", 1234, 0, 0);
	Sleep(500);


	printf("Tests multiple threads sharing the same instance of RakPeer\n");
	printf("Difficulty: Beginner\n\n");

	printf("Don't forget to define _RAKNET_THREADSAFE in RakNetDefines.h for this test!\n");


	endThreads=false;
	unsigned threadId;
	unsigned i;
	char count[20];
	printf("Starting threads\n");
	for (i=0; i< 10; i++)
	{
		count[i]=i;
		_beginthreadex( NULL, 0, ProducerThread, count+i, 0, &threadId );
	}
	for (; i < 20; i++)
	{
		count[i]=i;
		_beginthreadex( NULL, 0, ConsumerThread, count+i, 0, &threadId );
	}

	printf("Running test\n");
	RakNetTime endTime = 60 * 1000 + RakNet::GetTime();
	while (RakNet::GetTime() < endTime)
	{

		Sleep(0);
	}
	endThreads=true;
	printf("Test done!\n");

	RakNetworkFactory::DestroyRakPeerInterface(peer1);
	RakNetworkFactory::DestroyRakPeerInterface(peer2);
}
Example #20
0
	ServerClient::ServerClient()
		:m_port(8099),m_connected(false),
		m_connecting(false),m_server(NULL),m_bgMode(false)
	{
		m_server = RakNet::RakPeerInterface::GetInstance();

		// Connecting the client is very simple.  0 means we don't care about
		// a connectionValidationInteger, and false for low priority threads
		RakNet::SocketDescriptor socketDescriptor(0,0);
		socketDescriptor.socketFamily=AF_INET;
		m_server->Startup(8,&socketDescriptor, 1);
		m_server->SetOccasionalPing(true);
		//m_server->SetTimeoutTime(15000,RakNet::UNASSIGNED_SYSTEM_ADDRESS);

	}
Example #21
0
long ExtObject::aHostServer(LPVAL params)
{
	server = true;

	int port = params[0].GetInt();
	string password = params[1].GetString();

	raknet->SetIncomingPassword(password.c_str(), password.length());
	raknet->SetTimeoutTime(30000,RakNet::UNASSIGNED_SYSTEM_ADDRESS);

	RakNet::SocketDescriptor socketDescriptor( port, 0);
	bool b = raknet->Startup(4, &socketDescriptor, 1 ) == RakNet::RAKNET_STARTED;
	raknet->SetMaximumIncomingConnections(20);

	return 0;
}
void Session::processRpcAnswer(QByteArray response) {

    qint32 op;
    peekIn(&op, 4);
    qint32 len = response.length();

    qCDebug(TG_CORE_SESSION) << "connection #" << socketDescriptor() << "received rpc answer" << op << "with" << len << "content bytes by session" << QString::number(m_sessionId, 16);

    InboundPkt p(response.data(), len);

    if (op < 0 && op >= -999) {
        qCDebug(TG_CORE_SESSION) << "server error" << op;
    } else {
        processRpcMessage(p);
    }
}
Example #23
0
void Network::Init( int clientPort, std::string ip, int serverPort )
{
	//
	RakNetStatistics *rss;
	_client=RakNetworkFactory::GetRakPeerInterface();
	_client->AllowConnectionResponseIPMigration(false);	
	
	//
	SocketDescriptor socketDescriptor( clientPort, 0 );
	_client->Startup(1,30,&socketDescriptor, 1);
	_client->SetOccasionalPing(true);
	BOOL b = _client->Connect(ip.c_str(), serverPort, "Rumpelstiltskin", (int) strlen("Rumpelstiltskin"));	
	if (!b)
	{
		exit(1);
	}
}
Example #24
0
QVariant Request::data(int role) const
{
    switch (role) {
    case methodRole:
        return m_method;

    case argumentRole:
        return m_argument;

    case hostRole:
        return QString("%1 (%2)").arg(m_host).arg(socketDescriptor());

    case peerAddressRole:
        return m_peerAddress;

    case statusRole:
        return m_status;

    case headerRole:
        return m_header.join("");

    case contentRole:
        return m_content;

    case durationRole:
        return QTime(0, 0).addMSecs(m_duration).toString("hh:mm:ss.zzz");

    case dateRole:
        return m_date;

    case answerRole:
        return m_stringAnswer.join("");

    case networkStatusRole:
        return m_networkStatus;

    case transcodeLogRole:
        return requestLog;

    default:
        return QVariant::Invalid;

    }

    return QVariant::Invalid;
}
Example #25
0
bool AbstractSocket::listen()
{
	if (isClosed()) 
	{
		//printf("AbstractSocket::bind not opened socket\n");
		return false;
	}

	int backlog = 0;
	if (::listen(socketDescriptor(), backlog) == -1)
	{
		//printf("AbstractSocket::listen failed to listen\n");
		return false;
	}

	return true;
}
Example #26
0
void AbstractSocket::setBlocking(bool f)
{
	int sockfd = socketDescriptor();
#ifndef WIN32
	int flags = fcntl(sockfd, F_GETFL, 0);
	if (!f) fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
	else fcntl(sockfd, F_SETFL, flags ^ O_NONBLOCK);
#else
	int nonblocking =1;
	if (f) nonblocking = 0;

	if (ioctlsocket(sockfd,FIONBIO, (u_long*)&nonblocking) == SOCKET_ERROR)  
	{
		close();
		return;
	}
#endif	
}
void Connection::setupSocket() {
    // See: http://goo.gl/0pjCQo
    // setSocketOption(QAbstractSocket::KeepAliveOption, 1);

#ifdef Q_OS_LINUX
    int enableKeepAlive = 1;
    int fd = socketDescriptor();
    setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &enableKeepAlive, sizeof(enableKeepAlive));

    int maxIdle = 10; // half seconds = 5 seconds
    setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &maxIdle, sizeof(maxIdle));

    int count = 3; // send up to 3 keepalive packets out, then disconnect if no response
    setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &count, sizeof(count));

    int interval = 2; // send a keepalive packet out every 2 seconds (after the first idle period)
    setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &interval, sizeof(interval));
#endif
}
Example #28
0
	bool NetStream::startConnect (const char* ip, int port)
	{
		pPeer->SetTimeoutTime(5000,RakNet::UNASSIGNED_SYSTEM_ADDRESS);
		RakNet::SocketDescriptor socketDescriptor(0,0);
		socketDescriptor.socketFamily=AF_INET;
		RakNet::StartupResult sr;
		sr=pPeer->Startup(MAX_CONNECTION, &socketDescriptor, 1);
		if (sr!=RakNet::RAKNET_STARTED)
		{
			//fail
			return false;
		}
		pPeer->SetSplitMessageProgressInterval(10000); // Get ID_DOWNLOAD_PROGRESS notifications
		//	client->SetPerConnectionOutgoingBandwidthLimit(28800);

//		printf("Started client on %s\n", client->GetMyBoundAddress().ToString(true));

		pPeer->Connect(ip, port, 0, 0);
		return true ;
	}
Example #29
0
long ExtObject::aConnect(LPVAL params)
{
	string ip = params[0].GetString();
	int remotePort = params[1].GetInt();	
	int localPort = params[2].GetInt();
	string password = params[3].GetString();

	RakNet::SocketDescriptor socketDescriptor(localPort,0);
	if (raknet->Startup(1, &socketDescriptor, 1)==RakNet::RAKNET_STARTED)
	{
		raknet->SetOccasionalPing(true);
		if (raknet->Connect(ip.c_str(), remotePort, password.c_str(), password.length())==RakNet::CONNECTION_ATTEMPT_STARTED)
			printf("Connecting...\nNote: if the password is wrong the other system will ignore us.\n");
		else
			printf("Connect call failed.\n");
	}
	else
		printf("Initialize call failed.\n");	

	return 0;
}
bool MulticastSocket::joinMulticastGroup(const QHostAddress& groupAddress, const QNetworkInterface& iface)
{
    bool success = false;

    foreach (const QNetworkAddressEntry& addressEntry, iface.addressEntries()) {
        const QHostAddress interfaceAddress = addressEntry.ip();

        if (interfaceAddress.protocol() == IPv4Protocol) {
            ip_mreq mreq;
            mreq.imr_multiaddr.s_addr = htonl(groupAddress.toIPv4Address());
            mreq.imr_interface.s_addr = htonl(interfaceAddress.toIPv4Address());

            const bool error = setsockopt(socketDescriptor(), IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char*) &mreq, sizeof(mreq)) == -1;
            if (error)
                setErrorString(strerror(errno));
            else
                success = true;
        }
    }

    return success;
}