#include
#include
#ifndef WIN32
#include
#include
#include
#include
#include
#define closesocket(a) close(a)
#else
#include
#endif
#define PORT 1234
#define MAXSOCKFD 10
int main() {
#ifdef WIN32
WSADATA wsaData;
WORD wVersionRequested = MAKEWORD( 2, 2 );
WSAStartup(wVersionRequested, &wsaData);
#endif
SOCKET sockfd, newsockfd, is_connected[MAXSOCKFD], fd;
int i;
struct sockaddr_in addr;
int addr_len = sizeof(struct sockaddr_in);
fd_set readfds;
char buffer[256];
char msg[] = "Welcome to server!";
if ((sockfd = socket(AF_INET,SOCK_STREAM, 0)) < 0) {
perror("socket");
exit(1);
}
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sockfd, (struct sockaddr*) &addr, sizeof(addr)) < 0) {
perror("connect");
exit(1);
}
if (listen(sockfd, 5) < 0) {
perror("listen");
exit(1);
}
for (i = 0; i < MAXSOCKFD; i++)
is_connected[i] = 0;
is_connected[0] = sockfd;
while (1) {
newsockfd = sockfd;
FD_ZERO(&readfds);
for (i = 0; i < MAXSOCKFD; i++)
if (is_connected[i])
{
FD_SET(is_connected[i],&readfds);
if(newsockfd
send(newsockfd, msg, sizeof(msg), 0);
for (fd = 0; fd < MAXSOCKFD; fd++)
if (is_connected[fd] == 0)
is_connected[fd] = newsockfd;
printf("cnnect from %s\n", inet_ntoa(addr.sin_addr));
} else {
memset(buffer, 0, sizeof(buffer));
if (recv(is_connected[i], buffer, sizeof(buffer), 0)
<= 0) {
printf("connect closed %d.\n",is_connected[i]);
closesocket(is_connected[i]);
FD_CLR(is_connected[i],&readfds);
is_connected[i] = 0;
} else {
send(is_connected[i], buffer, sizeof(buffer), 0);
printf("%s", buffer);
}
}
}
}
}
#ifdef WIN32
WSACleanup();
#endif
return 0;
}
//仅仅是例子,写程序时查语法用
阅读(2845) | 评论(0) | 转发(0) |