I am a newbie at websocket programming. Currently I am working on a simple websocket server,using c, that can respond to a websocket client. I managed to get that working with 1 client and 1 server on a single port. I want to know if I could open 2 ports, so different clients could connect to the the different ports.
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[])
{
int listenfd = 0, connfd = 0;
struct sockaddr_in serv_addr;
char sendBuff[1025];
listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, '0', sizeof(serv_addr));
memset(sendBuff, '0', sizeof(sendBuff));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY );
serv_addr.sin_port = htons(8000);
bind(listenfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr));
listen(listenfd, 10);
while (1)
{
connfd = accept(listenfd, (struct sockaddr*) NULL, NULL );
close(connfd);
sleep(1);
}
}
解决方案
If you want multiple clients for 1 server, you need to use threading, you listen, then when you accept a client, create a thread and have him manage the request, and make the main thread go back to listening.
Different ports is kinda difficult, because client needs to connect to a specific port, so how do you know which port to connect to, and thinking you want an undefined number of clients, or how do you manage which ports are free, and communicate it with to the client(and not iterate 1 by 1, on a port range).
I don't remember the C p_thread lib, but that would be a start.