/* minitalk サーバプログラム */
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
int CanIRecv(int fd){
fd_set fdset;
struct timeval timeout;
FD_ZERO( &fdset );
FD_SET( fd , &fdset );
timeout.tv_sec = 0;
timeout.tv_usec = 0;
return select( fd+1 , &fdset , NULL , NULL , &timeout );
}
int main(int argc, char *argv[])
{
int srv_sock, *sock, port, m, i, j, size;
struct sockaddr_in srv_addr, cli_addr;
int addrlen, sendlen, recvlen;
char buf[256];
m = 0;
size = 0;
/* ポート番号を引数から取得 */
port
= strtol(argv
[1], NULL
, 10);
/* ソケットの作成 */
srv_sock = socket(AF_INET, SOCK_STREAM, 0);
if (srv_sock < 0) {
perror("cannot create socket"); }
/* サーバとしてバインド */
srv_addr.sin_family = AF_INET;
srv_addr.sin_port = htons(port);
srv_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(srv_sock, (struct sockaddr*)&srv_addr, sizeof(srv_addr)) < 0) {
}
/* 待ち受け人数を1人に設定 */
listen(srv_sock, 1);
/* 実際の通信 */
while (feof(stdin
) == 0) {
if(CanIRecv(srv_sock)){
/* クライアントからの接続を受け付ける */
addrlen = sizeof(cli_addr);
sock
= (int *)realloc(sock
, (size
+ 1) * sizeof(int) * (m
+ 1));
sock[m] = accept(srv_sock, (struct sockaddr*)&cli_addr, &addrlen);
if (sock[m] == -1) {
}
m++;
}
if(CanIRecv(0)){
/* 標準入力からキーボード入力された文字を読み込む */
fgets(buf
, sizeof(buf
), stdin
); for(i = 0; i <= m; i++){
/* 読み込んだ文字をソケットに書き込む */
sendlen
= write
(sock
[m
], buf
, strlen(buf
) + 1); if (sendlen < 0) {
perror("cannot send a message"); }
}
}
if (CanIRecv(sock[m])) {
/* ソケットからのデータを読み込む */
for(j = 0; j <= m; j++){
recvlen = read(sock[m], buf, sizeof(buf));
if (recvlen <= 0) {
/* クライアント側が EOF */
break;
}
}
}
}
/* これ以上クライアントを受け付けないので、サーバのソケットを閉じる */
close(srv_sock);
close(sock[m]);
}
LyogbWluaXRhbGsg44K144O844OQ44OX44Ot44Kw44Op44OgICovCiNpbmNsdWRlIDxzdGRpby5oPgojaW5jbHVkZSA8c3RkbGliLmg+CiNpbmNsdWRlIDxzeXMvdHlwZXMuaD4KI2luY2x1ZGUgPHN5cy9zb2NrZXQuaD4KI2luY2x1ZGUgPG5ldGRiLmg+CiNpbmNsdWRlIDxuZXRpbmV0L2luLmg+CgoKaW50IENhbklSZWN2KGludCBmZCl7IAoJZmRfc2V0IGZkc2V0OwoJc3RydWN0IHRpbWV2YWwgdGltZW91dDsKCUZEX1pFUk8oICZmZHNldCApOyAKCUZEX1NFVCggZmQgLCAmZmRzZXQgKTsKCXRpbWVvdXQudHZfc2VjID0gMDsgCgl0aW1lb3V0LnR2X3VzZWMgPSAwOwoJcmV0dXJuIHNlbGVjdCggZmQrMSAsICZmZHNldCAsIE5VTEwgLCBOVUxMICwgJnRpbWVvdXQgKTsKfQoKCmludCBtYWluKGludCBhcmdjLCBjaGFyICphcmd2W10pCnsKCWludCBzcnZfc29jaywgKnNvY2ssIHBvcnQsIG0sIGksIGosIHNpemU7CglzdHJ1Y3Qgc29ja2FkZHJfaW4gc3J2X2FkZHIsIGNsaV9hZGRyOwoJaW50IGFkZHJsZW4sIHNlbmRsZW4sIHJlY3ZsZW47CgljaGFyIGJ1ZlsyNTZdOwoJbSA9IDA7CglzaXplID0gMDsKCS8qIOODneODvOODiOeVquWPt+OCkuW8leaVsOOBi+OCieWPluW+lyAqLwoJcG9ydCA9IHN0cnRvbChhcmd2WzFdLCBOVUxMLCAxMCk7CgoJLyog44K944Kx44OD44OI44Gu5L2c5oiQICovCglzcnZfc29jayA9IHNvY2tldChBRl9JTkVULCBTT0NLX1NUUkVBTSwgMCk7CglpZiAoc3J2X3NvY2sgPCAwKSB7CgkJcGVycm9yKCJjYW5ub3QgY3JlYXRlIHNvY2tldCIpOwoJCWV4aXQoLTEpOwoJfQoKCS8qI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