我可以使用单个websocket服务器同时打开2个端口吗 [英] Can I open 2 ports simultaneously with single websocket server

查看:1251
本文介绍了我可以使用单个websocket服务器同时打开2个端口吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是websocket编程的新手.目前,我正在使用c的简单Websocket服务器上工作,该服务器可以响应Websocket客户端.我设法在单个端口上使用1个客户端和1个服务器来实现该功能.我想知道是否可以打开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 <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>

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);
  }
}

推荐答案

如果要为一台服务器使用多个客户端,则需要使用线程,您需要侦听,然后在接受客户端时,创建一个线程并让他管理请求,并使主线程返回到侦听状态. 不同的端口有点困难,因为客户端需要连接到特定的端口,因此您如何知道要连接到哪个端口,并认为您需要数量不确定的客户端,或者如何管理空闲的端口并进行通信到客户端(而不是在端口范围上逐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).

我不记得C p_thread库,但这只是一个开始.

I don't remember the C p_thread lib, but that would be a start.

这篇关于我可以使用单个websocket服务器同时打开2个端口吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆