2014年4月23日水曜日

開発環境

Head First C ―頭とからだで覚えるCの基本(David Griffiths (著)、Dawn Griffiths (著) 中田 秀基(監訳)(翻訳)、木下 哲也 (翻訳)、オライリージャパン)の11章(ソケットとネットワーキング)、長いエクササイズ(p.481)を解いてみる。

その他参考書籍

長いエクササイズ(p.481)

コード(BBEdit, Emacs)

sample480.c

#include <stdio.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];

  if (listen(listener_d, 10) == -1)
    error("接続待ちできません");

  puts("接続を待っています");
  while (1) {
    struct sockaddr_storage client_addr;
    unsigned int address_size = sizeof(client_addr);
    int connect_d = accept(listener_d, (struct sockaddr *) &client_addr,
                           &address_size);
    if (connect_d == -1)
      error("第2のソケットを開けません");
    if (say(connect_d, "Knock! Knock!\r\n") != -1) {
      read_in(connect_d, msg, sizeof(msg));
      if (strncmp("Who's there?", msg, 12) == 0) {
        if (say(connect_d, "Oscar\r\n") != -1) {
          read_in(connect_d, msg, sizeof(msg));
          if (strncmp("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);
  }
  
  return (0);
}

Makefile

all: sample480

sample480: sample480.c error.o server_client.o
 cc -g -o sample480 sample480.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 sample480

入出力結果(Terminal)

$ make
cc -g -o sample480 sample480.c error.o server_client.o
$ ./sample480
接続を待っています
^Z
[1]+  Stopped                 ./sample480
$ bg
[1]+ ./sample480 &
$ 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.
$ telnet 127.0.0.1 30000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Knock! Knock!
Who?
「Who's there?」と入力してください
Connection closed by foreign host.
$ telnet 127.0.0.1 30000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Knock! Knock!
Who's there?
Oscar
Oscar?
「Oscar who?」と入力してください
Connection closed by foreign host.
$ fg
./sample480
^Cさようなら!
$

0 コメント:

コメントを投稿