[英]send() to specific client C WInSock
當我有多個客戶端連接時,我將如何發送給特定的客戶端。 我想到過sendto();
但是我都在同一個套接字上運行它們,但是我不確定是否可以將它們的addr存儲為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);
返回0; }
您可以通過將數據send
到與該客戶端連接的套接字來將數據send
到該客戶端。
這是您已經在做的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.