客户端部分

来源:互联网 发布:传奇霸业轮回升级数据 编辑:程序博客网 时间:2024/05/01 10:43

来自:http://www.codeproject.com/Articles/412511/Simple-client-server-network-using-Cplusplus-and-W

这里做了一些修改,当然还需做进一步完善。

包含四个文件:

ClientNetwork.h  //客户端socket的初始化,数据收发
ClientNetwork.cpp

ClientGame.h
ClientGame.cpp //客户端收据收发的处理

// Networking libraries#include <winsock2.h>#include <ws2tcpip.h>// port to connect sockets through #define DEFAULT_PORT "6881"class ClientNetwork{public:    // socket for client to connect to server    SOCKET ConnectSocket;    // ctor/dtor    ClientNetwork(void);    ~ClientNetwork(void);int receivePackets(char *);};

#include "StdAfx.h"#include <stdio.h> #include "ClientNetwork.h"#include "NetworkServices.h"#include "NetworkData.h"ClientNetwork::ClientNetwork(void){int iResult;    // create WSADATA object    WSADATA wsaData;    // socket    ConnectSocket = INVALID_SOCKET;    // holds address info for socket to connect to    struct addrinfo *result = NULL,                    *ptr = NULL,                    hints;    // Initialize Winsock    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);    if (iResult != 0) {        printf("WSAStartup failed with error: %d\n", iResult);        exit(1);    }    // set address info    ZeroMemory(&hints, sizeof(hints));    hints.ai_family   = AF_UNSPEC;//协议无关    hints.ai_socktype = SOCK_STREAM;//流    hints.ai_protocol = IPPROTO_TCP;//TCP connection!!!    //resolve server address and port     iResult = getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result);    if (iResult != 0 )     {        printf("getaddrinfo failed with error: %d\n", iResult);        WSACleanup();        exit(1);    }    //Attempt to connect to an address until one succeeds    for (ptr = result; ptr != NULL; ptr = ptr->ai_next){        // Create a SOCKET for connecting to server        ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,             ptr->ai_protocol);        if (ConnectSocket == INVALID_SOCKET) {            printf("socket failed with error: %ld\n", WSAGetLastError());            WSACleanup();            exit(1);        }        // Connect to server.        iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);        if (iResult == SOCKET_ERROR)        {            closesocket(ConnectSocket);            ConnectSocket = INVALID_SOCKET;            printf ("The server is down... did not connect");        }    }    // no longer need address info for server    freeaddrinfo(result);    // if connection failed    if (ConnectSocket == INVALID_SOCKET)     {        printf("Unable to connect to server!\n");        WSACleanup();        exit(1);    }// Set the mode of the socket to be nonblocking    u_long iMode = 1;    iResult = ioctlsocket(ConnectSocket, FIONBIO, &iMode);    if (iResult == SOCKET_ERROR)    {        printf("ioctlsocket failed with error: %d\n", WSAGetLastError());        closesocket(ConnectSocket);        WSACleanup();        exit(1);            }//disable nagle    char value = 1;    setsockopt( ConnectSocket, IPPROTO_TCP, TCP_NODELAY, &value, sizeof( value ) );}ClientNetwork::~ClientNetwork(void){}int ClientNetwork::receivePackets(char * recvbuf) {int iResult;    iResult = NetworkServices::receiveMessage(ConnectSocket, recvbuf, MAX_PACKET_SIZE);    if (iResult == 0)    {        printf("Connection closed\n");        closesocket(ConnectSocket);        WSACleanup();        exit(1);    }    return iResult;}

#include "ClientNetwork.h"#include "NetworkData.h"class ClientGame{public:ClientGame(void);~ClientGame(void);    void update();private:char network_data[MAX_PACKET_SIZE];ClientNetwork* network;void sendActionPackets();};

ClientGame::ClientGame(void){    network = new ClientNetwork();    // send init packet    const unsigned int packet_size = sizeof(Packet);    char packet_data[packet_size];    Packet packet;    packet.packet_type = INIT_CONNECTION;    packet.serialize(packet_data);    NetworkServices::sendMessage(network->ConnectSocket, packet_data, packet_size);}ClientGame::~ClientGame(void){}void ClientGame::sendActionPackets(){    // send action packet    const unsigned int packet_size = sizeof(Packet);    char packet_data[packet_size];    Packet packet;    packet.packet_type = ACTION_EVENT;    packet.serialize(packet_data);    NetworkServices::sendMessage(network->ConnectSocket, packet_data, packet_size);}void ClientGame::update(){    Packet packet;    int data_length = network->receivePackets(network_data);    if (data_length <= 0)     {        //no data recieved        return;    }    unsigned int i = 0;    while (i < (unsigned int)data_length)     {        packet.deserialize(&(network_data[i]));        i += sizeof(Packet);        switch (packet.packet_type) {case ACTION_EVENT:                printf("client received action event packet from server\n");                sendActionPackets();                break;            default:                printf("error in packet types\n");                break;        }    }}

简单使用:

void clientLoop(void);ClientGame * client;int main(){       // initialize the client client = new ClientGame();clientLoop();}void clientLoop(){while(true){//do game stuffclient->update();}}




原创粉丝点击