[英]send() to specific client C WInSock
How would I send to a specific client when I have multiple clients connected. 当我有多个客户端连接时,我将如何发送给特定的客户端。 I've thought of
sendto();
我想到过
sendto();
But I run all of them on the same socket and i am unsure of a way to store their addr for sendto()
. 但是我都在同一个套接字上运行它们,但是我不确定是否可以将它们的addr存储为
sendto()
。 SO maybe my way of accepting multiple clients isn't very good? 所以,也许我接受多个客户的方式不是很好吗?
My Server Code: 我的服务器代码:
#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; 返回0; }
}
You would send data to a specific client by send
ing it to a socket connected to that client. 您可以通过将数据
send
到与该客户端连接的套接字来将数据send
到该客户端。
Which is what you're already doing. 这是您已经在做的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.