我做了简单的 server.c 来做这个:
- 监听 7705 端口。
- 接受来自“Client-x”的传入连接。
- 当没有挂起的连接时,从“Client-1”接收数据。
- 如果有来自另一个客户端的挂起连接,则转到第二步。
这是代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) {
fprintf(stderr,"ERROR, no port ..\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
perror("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
p error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
accpt:
while (newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen) < 0)
{
/* i don't know return value for "there is no pending connection" in accept() function, so i use -1 value" */
bzero(buffer,256);
n = read(newsockfd,buffer,255);
....... // Process data, and etc //
}
goto accept
}