基于Win32的多线程客户/服务器通信

简介:
客户端:
复制代码
// Client.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "resource.h"
#include <winsock.h>

#pragma warning(disable:4700)

#define MAX_LOADSTRING 100

// Global Variables:
HINSTANCE hInst;                                // current instance
TCHAR szTitle[MAX_LOADSTRING];                    // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];            // The title bar text

// Foward declarations of functions included in this code module:
ATOM                MyRegisterClass(HINSTANCE hInstance);
BOOL                InitInstance(HINSTANCE, int);
LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK    About(HWND, UINT, WPARAM, LPARAM);

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
    // TODO: Place code here.
    MSG msg;
    HACCEL hAccelTable;

    // Initialize global strings
    LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
    LoadString(hInstance, IDC_CLIENT, szWindowClass, MAX_LOADSTRING);
    MyRegisterClass(hInstance);

    // Perform application initialization:
    if (!InitInstance (hInstance, nCmdShow)) 
    {
        return FALSE;
    }

    hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_CLIENT);

    // Main message loop:
    while (GetMessage(&msg, NULL, 0, 0)) 
    {
        if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) 
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    int wmId, wmEvent;
    PAINTSTRUCT ps;
    HDC hdc;
    TCHAR szHello[MAX_LOADSTRING];
    LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING);

    WORD version;    //used to store the socket version
    WSADATA wsaData;    //used to store info about socket
    SOCKET theSocket;    //used to create client socket
    SOCKADDR_IN serverInfo;    //used to specify a local or remote endpoint address to which to connect a socket
    int rVal;    //used to store return value
    LPHOSTENT hostEntry;    //Windows Sockets allocates this structure
    char *buf = "Data On Socket";    //Data to be send on socket

    char data[5];
    switch (message) 
    {
    case WM_COMMAND:
        wmId    = LOWORD(wParam); 
        wmEvent = HIWORD(wParam); 
        // Parse the menu selections:
        switch (wmId)
        {
        case IDM_ABOUT:
            DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About);
            break;
        case IDM_EXIT:
            DestroyWindow(hWnd);
            break;
        case IDM_COMMUNICATE:
            //get the version of socket
            version = MAKEWORD(1,1);
            //The Windows Sockets WSAStartup function initiates use of WS2_32.DLL by a process
            rVal = WSAStartup(version,(LPWSADATA)&wsaData);
            //store information about the server
            //Here we are suppose to pass the server information to the client,
            //so that the client knows where is the server
            //I am using the machine name on wich my server.exe is running
            hostEntry = gethostbyname("seclore3");
            if(!hostEntry)
            {
                MessageBox(hWnd,"Failed in gethostbyname API","Gethostbyname Error",MB_OK);
                WSACleanup();
                break;
            }
            //here we are creating the socket
            theSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
            if(theSocket == SOCKET_ERROR)
            {
                MessageBox(hWnd,"Failed in socket API","Socket Error",MB_OK);
            }
            //Fill in the sockaddr_in struct
            serverInfo.sin_family = PF_INET;
            serverInfo.sin_addr = *((LPIN_ADDR)*hostEntry->h_addr_list);
            serverInfo.sin_port = htons(8888);
            //Connect to the socket we just created                
            rVal=connect(theSocket,(LPSOCKADDR)&serverInfo, sizeof(serverInfo));
            if(rVal==SOCKET_ERROR)
            {
                MessageBox(hWnd,"Failed in connect API","Connect Error",MB_OK);
                break;
            }
            //Send the data to the server
            rVal = send(theSocket, buf, strlen(buf), 0);
            if(rVal == SOCKET_ERROR)
            {
                MessageBox(hWnd,"Failed send","Send Error",MB_OK);
            }
            //Get/Recieve the data sent by the server
            rVal = recv(theSocket,data,5,0);
            if(rVal)
            {
                MessageBox(hWnd,data,"Data from server",MB_OK);
            }
            break;
        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
        }
        break;
    case WM_PAINT:
        hdc = BeginPaint(hWnd, &ps);
        // TODO: Add any drawing code here
        RECT rt;
        GetClientRect(hWnd, &rt);
        DrawText(hdc, szHello, strlen(szHello), &rt, DT_CENTER);
        EndPaint(hWnd, &ps);
        break;
    case WM_DESTROY:
        //Close the socket
        closesocket(theSocket);
        //The WSACleanup function initiates no action 
        WSACleanup();
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

复制代码

服务器端:

复制代码
// Server.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "resource.h"
#include <winsock.h>

//function declaration
DWORD WINAPI ValidateData(LPVOID Parameter);

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
    WORD sockVersion;    //Used to store socket version information
    WSADATA wsaData;    //used to store info about socket
    SOCKET s,client;    //used to create client and server socket
    SOCKADDR_IN sin;    //used to specify a local or remote endpoint address to which to connect a socket
    int rVal;    //used to store return value

    HANDLE hThread;    //Handle to thread
    DWORD ThreadId;    //used to store the thread id

    //Get the current socket version
    sockVersion = MAKEWORD(1,1);
    //初始化Socket库
    //The Windows Sockets WSAStartup function initiates use of WS2_32.DLL by a process
    WSAStartup(sockVersion, &wsaData);
    //here we are creating the socket
    s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(s == INVALID_SOCKET)
    {
        MessageBox(0,"Invalid socket","Socket Error",MB_OK);
        WSACleanup();
    }
    //fill in sockaddr_in struct 
    sin.sin_family = PF_INET;
    sin.sin_port = htons(8888);//监听端口为
    sin.sin_addr.s_addr = INADDR_ANY;

    //bind to the socket
    rVal = bind(s, (LPSOCKADDR)&sin, sizeof(sin));
    if(rVal == SOCKET_ERROR)
    {
        MessageBox(0,"Failed in bind API","Bind Error",MB_OK);
        WSACleanup();
    }

    //Listen to the desire port on which client suppose to connect
    rVal = listen(s, 2);//最大客户数目为
    if(rVal == SOCKET_ERROR)
    {
        MessageBox(0,"Failed in listen API","Listen Error",MB_OK);
        WSACleanup();
    }
    //infinite loop to serve all the clients which want service
    while(1)
    {
        //Accept the data from the client
        client = accept(s, NULL, NULL);//接受来自客户端的连接

        //Once the new client come up create a new thread t serve the client
        if(client)
        {//创建线程去处理此请求,将此连接作为参数传给处理线程
            hThread = CreateThread(NULL,
                0,
                ValidateData,
                (LPVOID)client,
                0,
                &ThreadId);
        }
        else
            return 0;
    }
    return 0;
}

DWORD WINAPI ValidateData(LPVOID Parameter)
{
    //Get the information about client entity
    SOCKET client = (SOCKET)Parameter;
    int rVal;    //Return val
    //数据缓冲区
    char buf[11];    //used to send the validated data to client

    //Get the data form client
    //接收数据
    rVal = recv(client,buf,11,0);
    //here we are performing simple check, the data came form client
    //is valid or not
    //at this point you can check your own data also, which needs some modification
    //回传数据给客户端
    if(strcmp(buf,"Data On Socket"))
    {
        //Send back the data to the client
        rVal = send(client,"YES",3,0);
    }
    else
    {
        //Send back the data to the client
        rVal = send(client,"NO",2,0);
    }
    return 0;
}

复制代码



本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2008/07/14/1242960.html,如需转载请自行联系原作者
目录
相关文章
|
安全 Java 调度
Java编程时多线程操作单核服务器可以不加锁吗?
Java编程时多线程操作单核服务器可以不加锁吗?
461 2
|
API Windows
揭秘网络通信的魔法:Win32多线程技术如何让服务器化身超级英雄,同时与成千上万客户端对话!
【8月更文挑战第16天】在网络编程中,客户/服务器模型让客户端向服务器发送请求并接收响应。Win32 API支持在Windows上构建此类应用。首先要初始化网络环境并通过`socket`函数创建套接字。服务器需绑定地址和端口,使用`bind`和`listen`函数准备接收连接。对每个客户端调用`accept`函数并在新线程中处理。客户端则通过`connect`建立连接,双方可通过`send`和`recv`交换数据。多线程提升服务器处理能力,确保高效响应。
362 6
|
Java
Java使用FileInputStream&&FileOutputStream模拟客户端向服务器端上传文件(单线程)
Java使用FileInputStream&&FileOutputStream模拟客户端向服务器端上传文件(单线程)
365 1
如何在Java中实现多线程的Socket服务器?
在Java中,多线程Socket服务器能同时处理多个客户端连接以提升并发性能。示例代码展示了如何创建此类服务器:监听指定端口,并为每个新连接启动一个`ClientHandler`线程进行通信处理。使用线程池管理这些线程,提高了效率。`ClientHandler`读取客户端消息并响应,支持简单的文本交互,如发送欢迎信息及处理退出命令。
645 2
|
11月前
|
弹性计算 运维 安全
阿里云轻量应用服务器与云服务器ECS啥区别?新手帮助教程
阿里云轻量应用服务器适合个人开发者搭建博客、测试环境等低流量场景,操作简单、成本低;ECS适用于企业级高负载业务,功能强大、灵活可扩展。二者在性能、网络、镜像及运维管理上差异显著,用户应根据实际需求选择。
902 10
|
11月前
|
弹性计算 ice
阿里云4核8g服务器多少钱一年?1个月和1小时价格,省钱购买方法分享
阿里云4核8G服务器价格因实例类型而异,经济型e实例约159元/月,计算型c9i约371元/月,按小时计费最低0.45元。实际购买享折扣,1年最高可省至1578元,附主流ECS实例及CPU型号参考。
918 8
|
11月前
|
运维 安全 Ubuntu
阿里云渠道商:服务器操作系统怎么选?
阿里云提供丰富操作系统镜像,涵盖Windows与主流Linux发行版。选型需综合技术兼容性、运维成本、安全稳定等因素。推荐Alibaba Cloud Linux、Ubuntu等用于Web与容器场景,Windows Server支撑.NET应用。建议优先选用LTS版本并进行测试验证,通过标准化镜像管理提升部署效率与一致性。
|
11月前
|
存储 监控 安全
阿里云渠道商:云服务器价格有什么变动?
阿里云带宽与存储费用呈基础资源降价、增值服务差异化趋势。企业应结合业务特点,通过阶梯计价、智能分层、弹性带宽等策略优化成本,借助云监控与预算预警机制,实现高效、可控的云资源管理。
|
11月前
|
弹性计算 运维 安全
区别及选择指南:阿里云轻量应用服务器与ECS云服务器有什么区别?
阿里云轻量应用服务器适合个人开发者、学生搭建博客、测试环境,易用且性价比高;ECS功能更强大,适合企业级应用如大数据、高流量网站。根据需求选择:轻量入门首选,ECS专业之选。
708 2
|
11月前
|
弹性计算 ice
阿里云4核8G云服务器配置价格:热门ECS实例及CPU处理器型号说明
阿里云2025年4核8G服务器配置价格汇总,涵盖经济型e实例、计算型c9i等热门ECS实例,CPU含Intel Xeon及AMD EPYC系列,月费159元起,年付低至1578元,按小时计费0.45元起,实际购买享折扣优惠。
3939 1