websocket 占用 端口_我可以使用单个websocket服务器同时打开2个端口吗

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值