send() 到特定的客户端 C WInSock

send() to specific client C WInSock

当我有多个客户端连接时,我将如何发送到特定客户端。我想到了 sendto(); 但我 运行 他们都在同一个套接字上,我不确定如何为 sendto() 存储他们的地址。所以也许我接受多个客户的方式不是很好?

我的服务器代码:

#include "stdafx.h"
#include <stdio.h>
#include <winsock.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
#define _WIN32_WINNIT 0x0500
#include <windows.h>
WSADATA wsa;
SOCKET sock, newsock;
int c;
int clientnum;
struct sockaddr_in server, client;

DWORD WINAPI ProcessClient(LPVOID lpParam) {
    SOCKET newSock = (SOCKET)lpParam;
    // Send and receive data.
    char buf[256];
    char newbuf[256];
    char cnumchar[5];
    strcpy(buf, "Hello Client #: ");
    itoa(clientnum, cnumchar, 10);
    strcat(buf, cnumchar);
    sendto(newSock, buf, sizeof(buf), 0, NULL, NULL);
    char sendbuf[256];
    strcpy(sendbuf, "a");
    while (1)
    {
        if (recv(newSock, newbuf, sizeof(newbuf), 0) == 0 || recv(newSock, newbuf, sizeof(newbuf), 0) == -1)  {
            printf("\nClient disconnected");
            clientnum--;
        }
        else if (send(newSock, sendbuf, sizeof(sendbuf), 0) == 0 || send(newSock, sendbuf, sizeof(sendbuf), 0) == -1) {
            printf("\nClient Disconnected!");
            clientnum--;
        }



    }

}

int main()
{

    printf("Initializing Winsock...\n");
    int ret = WSAStartup(MAKEWORD(2, 2), &wsa);
    if (ret != 0)
    {
        printf("Initialization Failed. Error: %d", ret);
        return 1;
    }
    printf("Initialized.\n");

    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sock == INVALID_SOCKET) {
        printf("Could not create socket! Error: %d\n", WSAGetLastError());
        return 1;
    }
    //textcolor(2);
    printf("Socket Created!\n");

    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(3939);

    //bind
    if (bind(sock, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR) {
        printf("Bind failed! Error: %d\n", WSAGetLastError());
        closesocket(sock);
        getch();
        return 1;
    }
    printf("Binded!\n");

    // listen
    if (listen(sock, 1) == SOCKET_ERROR) {
        printf("Listen failed! Error: %d\n", WSAGetLastError());
        closesocket(sock);
        return 1;
    }
    printf("Now Listening...\n");
    do {
        newsock = SOCKET_ERROR;
        do {
            newsock = accept(sock, NULL, NULL);
        } while (newsock == SOCKET_ERROR);
        printf("Client Connected!");
        DWORD dwThreadId;
        CreateThread(NULL, 0, ProcessClient, (LPVOID)newsock, 0, &dwThreadId);
        clientnum++;
    } while (true);

return 0; }

您可以通过 send 将数据发送到连接到该客户端的套接字来将数据发送到特定客户端。

这是您已经在做的事情。