Ejemplo n.º 1
0
void Application::newInstanceConnected() {
	DEBUG_LOG(("Application Info: new local socket connected"));
	for (QLocalSocket *client = server.nextPendingConnection(); client; client = server.nextPendingConnection()) {
		clients.push_back(ClientSocket(client, QByteArray()));
		connect(client, SIGNAL(readyRead()), this, SLOT(readClients()));
		connect(client, SIGNAL(disconnected()), this, SLOT(removeClients()));
	}
}
Ejemplo n.º 2
0
ClientSocket ServerSocket::next(int flags) {
  struct sockaddr_storage peer_addr;
  socklen_t peer_addr_size = sizeof(sockaddr_storage);
  memset(&peer_addr, 0, sizeof(peer_addr));

  //Poll the socket to see if a new connection has arrived
  //Wait until data is ready
  pollfd ufd;
  ufd.fd = sock_fd;
  ufd.events = POLLIN;
  //Wait up to 10 milliseconds for the poll to finish
  int result = poll(&ufd, 1, 10);
  //Accept a new socket is an input event is polled
  if (result == 1 and (ufd.revents & (POLLERR | POLLHUP | POLLNVAL)) == 0) {
    int in_sock = accept4(sock_fd, (struct sockaddr*)&peer_addr, &peer_addr_size, flags);

    std::string ip = "";

    if (0 <= in_sock) {
      //Get the ip address of this new connection
      char addr_buf[1000] = {0};
      int err = getnameinfo((struct sockaddr*)&peer_addr, peer_addr_size,
          addr_buf, sizeof(addr_buf) - 1, NULL, 0, NI_NUMERICHOST);
      if (err != 0) {
        std::cerr<<"Error getting client address: "<<gai_strerror(errno)<<'\n';
      }

      ip = std::string(addr_buf);
      std::cerr<<"Found ip address "<<addr_buf<<'\n';
    }
    //Don't print an error if the socket is simply non-blocking
    else if (errno != EAGAIN and errno != EWOULDBLOCK) {
      std::cerr<<"Socket failure: "<<strerror(errno)<<"\n";
    }

    //Control of the socket is handed over to the ClientSocket class.
    //The socket may be invalid if no new connection was available
    return ClientSocket(_port, ip, in_sock);
  }
  else {
    //Return an invalid socket
    return ClientSocket(_port, "", -1);
  }
}
Ejemplo n.º 3
0
void GameEngine::Initialize(const SDL_Rect& screenSize)
{
  std::cout << "GameEngine::Initialize" << std::endl;

  _socket = ClientSocket("0.0.0.0", "5001");

  SDL_Init(SDL_INIT_EVERYTHING);
  srand((unsigned int)time(NULL));

  // Soundstuff
  int audioRate = 22050;
  Uint16 audioFormat = AUDIO_S16SYS;
  int audioChannels = 2;
  int audioBuffers = 4096;

  if(Mix_OpenAudio(audioRate, audioFormat, audioChannels, audioBuffers) != 0)
  {
    std::cerr << "Unable to initialize audio: " << Mix_GetError()
      << std::endl;
    throw Mix_GetError();
  }

  // Activate anti-aliasing
  SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
  // Set AA level to 2
  SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 2);

  if (SDL_SetVideoMode(screenSize.x, screenSize.y, 32,
        SDL_HWSURFACE | SDL_GL_DOUBLEBUFFER | SDL_OPENGL) == NULL)
  {
    /* Ugly hack to make it work even if the system doesn't support
       multisampling. [FIXME]*/
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
    if (SDL_SetVideoMode(screenSize.x, screenSize.y, 32,
          SDL_HWSURFACE | SDL_GL_DOUBLEBUFFER | SDL_OPENGL) == NULL)
    {
      throw SDL_GetError();
    }
  }

  glViewport(0, 0, screenSize.x, screenSize.y);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0, screenSize.x, 0, screenSize.y, 1, -1);
  glMatrixMode(GL_MODELVIEW);
  glClearColor(0, 0.1f, 0, 1.0f);
  glClearDepth(1.0f);

  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  glAlphaFunc(GL_GREATER, 0.1f);

  PushState(new GSMain());
}
Ejemplo n.º 4
0
void RemoteSlaveProcess::Open(const char *host, int port, const char *cmdline, const char *envptr, int to)
{
    SVRLOG("RemoteSlaveProcess(" << host << ":" << port << ")=" << cmdline);
    Kill();

    timeout = to;
    Socket::Init();
    String localhost;
    if(host == 0 || *host == 0)
    {
        localhost = Socket::GetHostName();
        host = localhost;
    }
    if(port == 0)
        port = DEFAULT_PORT;
    terminated = false;
    current_part = 0;
    output[0] = output[1] = output[2] = Null;
    if(!ClientSocket(socket, host, port, true, NULL, REQUEST_TIMEOUT))
        throw Exc(NFormat(t_("Opening host '%s' / port %d failed, error = %s"), host, port, Socket::GetErrorText()));
    int len = (int)strlen(cmdline);
    if(envptr && *envptr) {
        const char *e = envptr;
        while(*e)
            e = e + strlen(e) + 1;
        socket.Write(":");
        socket.Write(ASCII85Encode(String(envptr, e + 1)));
        socket.Write("\n");
    }
    socket.Write("=");
    socket.Write(cmdline, len + 1); // send terminating 0 as well
    Recv(0, timeout);
    if(output[0][0] == '-')
        throw Exc(NFormat(t_("Error running process: %s\nCommand: %s"), output[0].Begin() + 1, cmdline));

    if(output[0] != "+")
        throw Exc(NFormat(t_("Communication error; process = %s"), cmdline));
}
Ejemplo n.º 5
0
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/,
    LPSTR /*lpCmdLine*/, int /*nShowCmd*/)
{
#ifdef _DEBUG
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
/*	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG);
	_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);
	_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG); */
//	_CrtSetBreakAlloc(254);
#endif
	
	hInst = hInstance;
	CoInitialize(NULL);

	WSADATA wsa;
	if (0 != WSAStartup(MAKEWORD(2, 0), &wsa))
		die("Failed to init network");

	SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0);

	struct sockaddr_in sin;
	memset(&sin, 0, sizeof sin);

	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = INADDR_ANY;
	sin.sin_port = htons(1338);

	if (SOCKET_ERROR == bind(serverSocket, (struct sockaddr *)&sin,
	    sizeof(sin)))
		die("Could not start server");

	while (listen(serverSocket, SOMAXCONN) == SOCKET_ERROR)
		; /* nothing */

	ATOM mainClass      = registerMainWindowClass(hInstance);
	ATOM trackViewClass = registerTrackViewWindowClass(hInstance);
	if (!mainClass || !trackViewClass)
		die("Window Registration Failed!");

	trackView = new TrackView();

	hwnd = CreateWindowExW(
		0,
		mainWindowClassName,
		mainWindowTitleW,
		WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
		CW_USEDEFAULT, CW_USEDEFAULT, // x, y
		CW_USEDEFAULT, CW_USEDEFAULT, // width, height
		NULL, NULL, hInstance, NULL
	);

	if (NULL == hwnd)
		die("Window Creation Failed!");

	int argc;
	LPWSTR *argv = argv = CommandLineToArgvW(GetCommandLineW(), &argc);
	if (argv && argc > 1) {
		if (argc > 2) {
			char prog[MAX_PATH];
			GetModuleFileNameA(NULL, prog, sizeof(prog));
			die("usage: %s [filename.rocket]", prog);
		}
		loadDocument(argv[1]);
	} else
		fileNew();
	
	HACCEL accel = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR));
	
	ShowWindow(hwnd, TRUE);
	UpdateWindow(hwnd);
	
	bool done = false;
	MSG msg;
	bool guiConnected = false;
	while (!done) {
		SyncDocument *doc = trackView->getDocument();
		if (!doc->clientSocket.connected()) {
			SOCKET clientSocket = INVALID_SOCKET;
			fd_set fds;
			FD_ZERO(&fds);
#pragma warning(suppress: 4127)
			FD_SET(serverSocket, &fds);
			struct timeval timeout;
			timeout.tv_sec = 0;
			timeout.tv_usec = 0;
			
			// look for new clients
			if (select(0, &fds, NULL, NULL, &timeout) > 0)
			{
				SendMessage(statusBarWin, SB_SETTEXT, 0, (LPARAM)"Accepting...");
				sockaddr_in client;
				clientSocket = clientConnect(serverSocket, &client);
				if (INVALID_SOCKET != clientSocket)
				{
					char temp[256];
					snprintf(temp, 256, "Connected to %s", inet_ntoa(client.sin_addr));
					SendMessage(statusBarWin, SB_SETTEXT, 0, (LPARAM)temp);
					doc->clientSocket = ClientSocket(clientSocket);
					clientIndex = 0;
					doc->clientSocket.sendPauseCommand(true);
					doc->clientSocket.sendSetRowCommand(trackView->getEditRow());
					guiConnected = true;
				}
				else SendMessage(statusBarWin, SB_SETTEXT, 0, (LPARAM)"Not Connected.");
			}
		}

		if (doc->clientSocket.connected()) {
			ClientSocket &clientSocket = doc->clientSocket;

			// look for new commands
			while (clientSocket.pollRead())
				processCommand(clientSocket);
		}

		if (!doc->clientSocket.connected() && guiConnected) {
			doc->clientSocket.clientPaused = true;
			InvalidateRect(trackViewWin, NULL, FALSE);
			SendMessage(statusBarWin, SB_SETTEXT, 0, (LPARAM)"Not Connected.");
			guiConnected = false;
		}
		
		while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			if (!TranslateAccelerator(hwnd, accel, &msg))
			{
				TranslateMessage(&msg);
				DispatchMessage(&msg);
				if (WM_QUIT == msg.message) done = true;
			}
		}
		Sleep(1);
	}

	closesocket(serverSocket);
	WSACleanup();

	delete trackView;
	trackView = NULL;

	UnregisterClassW(mainWindowClassName, hInstance);
	return int(msg.wParam);
}