基于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编程时多线程操作单核服务器可以不加锁吗?
142 2
|
7月前
|
网络协议 开发者 Python
Socket如何实现客户端和服务器间的通信
通过上述示例,展示了如何使用Python的Socket模块实现基本的客户端和服务器间的通信。Socket提供了一种简单且强大的方式来建立和管理网络连接,适用于各种网络编程应用。理解和掌握Socket编程,可以帮助开发者构建高效、稳定的网络应用程序。
310 10
|
12月前
|
存储 监控 NoSQL
Redis的实现二: c、c++的网络通信编程技术,让服务器处理多个client
本文讨论了在C/C++中实现服务器处理多个客户端的技术,重点介绍了事件循环和非阻塞IO的概念,以及如何在Linux上使用epoll来高效地监控和管理多个文件描述符。
130 1
|
API Windows
揭秘网络通信的魔法:Win32多线程技术如何让服务器化身超级英雄,同时与成千上万客户端对话!
【8月更文挑战第16天】在网络编程中,客户/服务器模型让客户端向服务器发送请求并接收响应。Win32 API支持在Windows上构建此类应用。首先要初始化网络环境并通过`socket`函数创建套接字。服务器需绑定地址和端口,使用`bind`和`listen`函数准备接收连接。对每个客户端调用`accept`函数并在新线程中处理。客户端则通过`connect`建立连接,双方可通过`send`和`recv`交换数据。多线程提升服务器处理能力,确保高效响应。
141 6
|
Java
Java使用FileInputStream&&FileOutputStream模拟客户端向服务器端上传文件(单线程)
Java使用FileInputStream&&FileOutputStream模拟客户端向服务器端上传文件(单线程)
178 1
|
网络协议 安全 Unix
6! 用Python脚本演示TCP 服务器与客户端通信过程!
6! 用Python脚本演示TCP 服务器与客户端通信过程!
259 1
|
网络协议 C# 开发者
WPF与Socket编程的完美邂逅:打造流畅网络通信体验——从客户端到服务器端,手把手教你实现基于Socket的实时数据交换
【8月更文挑战第31天】网络通信在现代应用中至关重要,Socket编程作为其实现基础,即便在主要用于桌面应用的Windows Presentation Foundation(WPF)中也发挥着重要作用。本文通过最佳实践,详细介绍如何在WPF应用中利用Socket实现网络通信,包括创建WPF项目、设计用户界面、实现Socket通信逻辑及搭建简单服务器端的全过程。具体步骤涵盖从UI设计到前后端交互的各个环节,并附有详尽示例代码,助力WPF开发者掌握这一关键技术,拓展应用程序的功能与实用性。
643 0
|
9天前
|
弹性计算 运维 安全
阿里云轻量应用服务器详解——2025升级到200M峰值带宽
阿里云轻量应用服务器(Simple Application Server)是面向个人开发者及中小企业的轻量级云服务,适用于网站搭建、开发测试、小程序后端等场景。2025年升级至200M峰值带宽,支持WordPress、宝塔面板、Docker等应用镜像一键部署,操作简单,运维便捷。按套餐售卖,不支持自定义CPU内存配置,价格低至38元/年起,是快速上云的高性价比选择。
|
1月前
|
存储 缓存 数据挖掘
阿里云目前最便宜云服务器介绍:38元、99元、199元性能,选购攻略参考
轻量应用服务器2核2G峰值200M带宽38元1年;云服务器经济型e实例2核2G3M带宽99元1年;云服务器通用算力型u1实例2核4G5M带宽199元1年。对于还未使用过阿里云服务器的用户来说,大家也不免有些疑虑,这些云服务器性能究竟如何?它们适用于哪些场景?能否满足自己的使用需求呢?接下来,本文将为您全方位介绍这几款云服务器,以供您了解及选择参考。
|
2月前
|
网络安全 云计算
如何设置阿里云轻量应用服务器镜像?
本文介绍了在阿里云轻量应用服务器上创建与配置镜像的详细步骤。镜像是一种特殊的文件系统映射,可用于快速克隆服务器配置。内容涵盖准备条件、登录控制台、创建实例、生成镜像、下载与设置镜像,以及如何使用镜像启动新实例。适合希望提升服务器部署效率的用户参考。