Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <QDebug>
- #include <QMessageBox>
- #include <winsock2.h>
- #define WIN32_LEAN_AND_MEAN
- #include <windows.h>
- #include "application.h"
- #include "defines.h"
- Application::Application(int argc, char** argv) :
- QApplication(argc, argv)
- {
- }
- bool
- Application::winEventFilter (MSG* msg, long*) {
- SOCKET acceptedSocket = 0;
- WSABUF winsockBuffer;
- DWORD nReceived = 0;
- DWORD nSent = 0;
- DWORD flags = 0;
- WSAOVERLAPPED* ol;
- if (msg->message == WM_SOCKET_TCP) {
- switch (WSAGETSELECTEVENT(msg->lParam)) {
- case FD_ACCEPT:
- if ((acceptedSocket = accept(msg->wParam, NULL, NULL)) == INVALID_SOCKET) {
- QMessageBox(QMessageBox::Critical, tr("Error"), tr("Error accepting on a socket")).exec();
- break;
- }
- WSAAsyncSelect(acceptedSocket, msg->hwnd, WM_SOCKET_TCP, FD_READ | FD_WRITE | FD_CLOSE);
- break;
- case FD_READ:
- winsockBuffer.len = DATA_BUFSIZE;
- winsockBuffer.buf = (char*) malloc(sizeof(char) * DATA_BUFSIZE);
- ol = (WSAOVERLAPPED*) malloc(sizeof(WSAOVERLAPPED));
- ol->hEvent = (HANDLE) winsockBuffer.buf;
- if (WSARecv((SOCKET) msg->wParam, &winsockBuffer, 1, &nReceived, &flags, ol, readCompleteRoutine) == SOCKET_ERROR) {
- if (WSAGetLastError() != WSA_IO_PENDING) {
- qDebug() << "error with WSARecv: " << WSAGetLastError();
- return true;
- }
- }
- break;
- case FD_WRITE:
- // set up a buffer with the specified size, full of the char 'n'
- winsockBuffer.len = HIWORD(msg->lParam);
- winsockBuffer.buf = (char*) malloc(sizeof(char) * HIWORD(msg->lParam));
- memset(winsockBuffer.buf, 'n', (int) HIWORD(msg->lParam));
- // allocate space for a new overlapped structure
- ol = (WSAOVERLAPPED*) malloc(sizeof(WSAOVERLAPPED));
- // since the event isnt used, store the buffer there to free it in the completion routine.
- ol->hEvent = (HANDLE) winsockBuffer.buf;
- if (WSASend((SOCKET) msg->wParam, &winsockBuffer, 1, &nSent, flags, ol, sendCompleteRoutine) == SOCKET_ERROR) {
- if (WSAGetLastError() != WSA_IO_PENDING) {
- qDebug() << "error with WSASend: " << WSAGetLastError();
- return true;
- }
- }
- break;
- case FD_CLOSE:
- closesocket((SOCKET) msg->wParam);
- break;
- }
- return true;
- }
- return false;
- }
- void CALLBACK sendCompleteRoutine(DWORD dwError, DWORD cbTransferred, LPWSAOVERLAPPED lpOverlapped, DWORD) {
- char* buf = (char*) lpOverlapped->hEvent;
- free(buf);
- free(lpOverlapped);
- }
- void CALLBACK readCompleteRoutine(DWORD dwError, DWORD cbTransferred, LPWSAOVERLAPPED lpOverlapped, DWORD) {
- qDebug() << "finished read" << cbTransferred;
- char* buf = (char*) lpOverlapped->hEvent;
- buf[cbTransferred] = '\0';
- qDebug() << buf;
- free(buf);
- free(lpOverlapped);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement