Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- altiscraft@overclock3000:~/DEV/AltisCraft.fr/Client$ cat Extensions/Network/Main/client.cpp
- #ifdef __linux__
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <netinet/ip.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <arpa/inet.h>
- #include <string.h>
- #include <fcntl.h>
- #define SOCKET int
- #define SOCKADDR_IN struct sockaddr_in
- #endif
- #ifdef _WIN32
- #include <winsock2.h>
- #endif
- #include <cstdio>
- #include <iostream>
- #include <thread>
- #include <string>
- #include "../Chat/chat.h"
- #include "../../Logger/logger.h"
- #include "../../AltisCraft.fr/Map/map.h"
- using namespace std;
- void initializeNetwork(), init(), connection(), receive(), sendStr(), closeConnection(), verifyDisconnexion();
- SOCKET socketId;
- SOCKADDR_IN destination;
- char buffer[65535];
- thread network, disconnected;
- bool connected = true;
- void initializeNetwork()
- {
- network = thread(&init);
- initializeChat();
- }
- void init()
- {
- #ifdef _WIN32
- WSADATA initWin32;
- WSAStartup(MAKEWORD(2, 2), &initWin32);
- #endif
- socketId = socket(AF_INET, SOCK_STREAM, 0);
- destination.sin_family = AF_INET; // inet_addr("199.188.236.18")
- destination.sin_addr.s_addr = *(u_long*)gethostbyname("altiscraft.fr")->h_addr_list[0];
- // inet_ntoa(addr) <- ipv4
- destination.sin_port = htons(33333);
- connection();
- disconnected = thread(&verifyDisconnexion);
- receive();
- closeConnection();
- }
- void sendStr(string str)
- {
- strcpy(buffer, str.c_str());
- send(socketId, buffer, strlen(buffer), 0);
- }
- void connection()
- {
- if(connect(socketId, (struct sockaddr*)&destination, sizeof(destination)) != 0)
- {
- log("Server not connected");
- connected = 0;
- }
- }
- void receive()
- {
- #ifdef _WIN32
- u_long mode = 1;
- ioctlsocket(socketId, FIONBIO, &mode);
- #endif
- #ifdef __linux__
- fcntl(socketId, F_SETFL, O_NONBLOCK);
- #endif
- sendStr("MAJ Map");
- while(1)
- {
- int length = recv(socketId, buffer, 1515, 0);
- if(length > 0)
- {
- buffer[length] = 0;
- string prefix("MAJ Map\n"), msg = buffer;
- log("Received: " + msg);
- if(!msg.compare(0, prefix.size(), prefix))
- loadMap(msg.substr(prefix.size()));
- else
- {
- log("Msg: " + msg);
- messageList.push_back(msg);
- }
- }
- if(connected == 0)
- break;
- }
- }
- void verifyDisconnexion()
- {
- char bufferTmp[1];
- while(1)
- {
- int lengthTemp = recv(socketId, bufferTmp, 1, 0), error = WSAGetLastError();
- if(lengthTemp == 0 && error == 0)
- sendStr(" ");
- if(error == 10053)
- {
- log("Server closed");
- connected = 0;
- break;
- }
- }
- }
- void closeConnection() /// FINE ? (like server)
- {
- shutdown(socketId, 2);
- #ifdef _WIN32
- closesocket(socketId);
- WSACleanup();
- #endif
- #ifdef __linux__
- close(socketId);
- #endif
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement