Head First C ―頭とからだで覚えるCの基本
(オライリージャパン)
David Griffiths (著) Dawn Griffiths (著)
中田 秀基(監訳)(翻訳) 木下 哲也 (翻訳)
開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- C (プログラミング言語)
- Clang (コンパイラ)
Head First C ―頭とからだで覚えるCの基本(David Griffiths (著)、Dawn Griffiths (著) 中田 秀基(監訳)(翻訳)、木下 哲也 (翻訳)、オライリージャパン)の11章(ソケットとネットワーキング)、自分で考えてみよう(p.488)を解いてみる。
その他参考書籍
- プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)
- プログラミング言語Cアンサー・ブック 第2版 (クロビス・L.トンド、スコット・E.ギンペル(著)、矢吹 道郎(翻訳))
- C実践プログラミング 第3版 (Steve Oualline (著)、 望月 康司 (監訳) (翻訳)、 谷口 功 (翻訳)、 オライリージャパン)
自分で考えてみよう(p.488)
コード(BBEdit, Emacs)
sample487.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <signal.h>
#include <string.h>
#include "error.h"
#include "server_client.h"
int main(int argc, char *argv[])
{
if (catch_signal(SIGINT, handle_shutdown) == -1)
error("割り込みハンドラを設定できません");
int listener_d = open_listener_socket();
bind_to_prot(listener_d, 30000);
char msg[100];
struct sockaddr_storage client_addr;
unsigned int address_size = sizeof(client_addr);
if (listen(listener_d, 10) == -1)
error("接続待ちできません");
puts("接続を待っています");
while (1) {
int connect_d = accept(listener_d, (struct sockaddr *) &client_addr,
&address_size);
if (connect_d == -1)
error("第2のソケットを開けません");
pid_t pid = fork();
if (!pid) {
close(listener_d);
if (say(connect_d, "Knock! Knock!\r\n") != -1) {
read_in(connect_d, msg, sizeof(msg));
if (strncasecmp("Who's there?", msg, 12) == 0) {
if (say(connect_d, "Oscar\r\n") != -1) {
read_in(connect_d, msg, sizeof(msg));
if (strncasecmp("Oscar who?", msg, 10) == 0)
say(connect_d,
"oscar silly question, you get a silly answer\r\n");
else
say(connect_d, "「Oscar who?」と入力してください\r\n");
}
}
else
say(connect_d, "「Who's there?」と入力してください\r\n");
}
close(connect_d);
exit (0);
}
close(connect_d);
}
return (0);
}
Makefile
all: sample487 sample487: sample487.c error.o server_client.o cc -g -o sample487 sample487.c error.o server_client.o server_client.o: server_client.c error.o cc -c -o server_client.o server_client.c error.o: error.c cc -c -o error.o error.c clean: rm -rf sample487
入出力結果(Terminal)
サーバー
$ make cc -g -o sample487 sample487.c error.o server_client.o $ ./sample487 接続を待っています ^Cさようなら! $
クライアント1
$ telnet 127.0.0.1 30000 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Knock! Knock! Who's there? Oscar Oscar who? oscar silly question, you get a silly answer Connection closed by foreign host. $
クライアント2(クライアント1と同時接続)
$ telnet 127.0.0.1 30000 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Knock! Knock! Who's there? Oscar Oscar who? oscar silly question, you get a silly answer Connection closed by foreign host. $
0 コメント:
コメントを投稿