Skip to content

Commit

Permalink
change the port number from 8000 to 8888.
Browse files Browse the repository at this point in the history
rename Java package name.
  • Loading branch information
ktabe committed Jul 5, 2024
1 parent 76ae7dc commit 73035d0
Show file tree
Hide file tree
Showing 10 changed files with 47 additions and 32 deletions.
7 changes: 4 additions & 3 deletions C#/webserver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@

class WebServer
{
const int SERVER_PORT = 8888;
static void Main(string[] args)
{
// 8000番ポートで listen する
var ep = new IPEndPoint(IPAddress.Any, 8000);
// SERVER_PORTで listen する
var ep = new IPEndPoint(IPAddress.Any, SERVER_PORT);
var listener = new TcpListener(ep);
try
{
Expand All @@ -24,7 +25,7 @@ static void Main(string[] args)
Console.WriteLine($"TcpListener.Start() failed: {e.ErrorCode}");
return;
}
Console.WriteLine("open http://localhost:8000/ with your browser!");
Console.WriteLine($"open http://localhost:{SERVER_PORT}/ with your browser!");

// クライアントからのコネクションを待ち受けるループ
while (true)
Expand Down
16 changes: 8 additions & 8 deletions C/webserver.c
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@
* Author: Kota Abe
*/

// Linux (CentOS7) とMacOS (10.14.6) で動作を確認済
// C99規格で書いているので,コンパイルには "cc -std=c99 webserver.c" とする
// Linux (Ubuntu22) とMacOS (10.14.6) で動作を確認済

#define _BSD_SOURCE // Linux requires for strdup()
#define _POSIX_C_SOURCE 200112L // for fdopen()
#define _DEFAULT_SOURCE

#include <stdio.h>
#include <stdlib.h>
Expand All @@ -20,6 +18,8 @@
void handle_get(FILE *fp, const char *path);
void handle_client(int client_fd, struct sockaddr_in *client_addr);

#define SERVER_PORT 8888

int main(int argc, char **argv)
{
// socket()はソケットを生成し,ファイル記述子(ソケットに割り当てられた整数値)を返す
Expand All @@ -43,7 +43,7 @@ int main(int argc, char **argv)
server_addr.sin_family = AF_INET; // IPv4アドレス
// サーバ側のIPアドレスはANY(指定しない).htonlは4バイトをネットワークバイトオーダに変換
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(8000); // サーバ側のポート番号の指定.htonsは2バイトをネットワークバイトオーダに変換
server_addr.sin_port = htons(SERVER_PORT); // サーバ側のポート番号の指定.htonsは2バイトをネットワークバイトオーダに変換
if (bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
perror("bind");
exit(1);
Expand All @@ -56,7 +56,7 @@ int main(int argc, char **argv)
exit(1);
}

printf("open http://localhost:8000/ with your browser!\n");
printf("open http://localhost:%d/ with your browser!\n", SERVER_PORT);

// クライアントからのコネクションを処理するためのループ
while (1) {
Expand Down Expand Up @@ -170,7 +170,7 @@ void handle_client(int client_fd, struct sockaddr_in *client_addr)
*/
void handle_get(FILE *fp, const char *path)
{
if (strcmp(path, "/") == 0) { // http://localhost:8000/ へのアクセスの場合
if (strcmp(path, "/") == 0) { // http://localhost:8888/ へのアクセスの場合
// C言語では連続した文字列は自動的に連結される
fprintf(fp,
"HTTP/1.0 200 OK\r\n" // ステータス行
Expand All @@ -182,7 +182,7 @@ void handle_get(FILE *fp, const char *path)
"<body>This server is implemented in C!</body>\r\n"
"</html>\r\n"
);
} else { // 他のパス (http://localhost:8000/abc.html) などへのアクセスの場合,404エラー
} else { // 他のパス (http://localhost:8888/abc.html) などへのアクセスの場合,404エラー
fprintf(fp,
"HTTP/1.0 404 Not Found\r\n" // 404はNot Foundを表す
"Content-Type: text/html\r\n"
Expand Down
5 changes: 3 additions & 2 deletions Elixir/webserver.exs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ defmodule WebServer do
Author: Kota Abe
"""
def main(_args \\ []) do
{:ok, socket} = :gen_tcp.listen(8000,
server_port = 8888
{:ok, socket} = :gen_tcp.listen(server_port,
[:binary, packet: :line, active: false, reuseaddr: true])
IO.puts("open http://localhost:8000/ with your browser!")
IO.puts("open http://localhost:#{server_port}/ with your browser!")
loop_acceptor(socket)
end

Expand Down
1 change: 1 addition & 0 deletions Go/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module main
8 changes: 5 additions & 3 deletions Go/webserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@ import (
"strings"
)

const SERVER_PORT = 8888

func main() {
// 8000番ポートで listen する
listener, err := net.Listen("tcp", ":8000")
// SERVER_PORTでlistenする
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", SERVER_PORT))
if err != nil {
panic("ListenTCP failed")
}
fmt.Println("open http://localhost:8000/ with your browser!")
fmt.Printf("open http://localhost:%d/ with your browser!\n", SERVER_PORT)

// クライアントからのコネクションを待ち受けるループ
for {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* A simple Web server implementation in Java
* Author: Kota Abe
*/
package ocu;
package webserver;

import java.io.*;
import java.net.InetSocketAddress;
Expand All @@ -12,11 +12,12 @@
import java.util.List;

public class WebServer {
static int SERVER_PORT = 8888;
public WebServer() {
// サーバソケットを作るには,ServerSocketのインスタンスを生成する
// このtryはtry-with-resource文 (スコープを抜けると自動的にserver.close()が呼ばれる)
try (ServerSocket server = new ServerSocket()) {
server.bind(new InetSocketAddress(8000)); // ポート番号の指定
server.bind(new InetSocketAddress(SERVER_PORT)); // ポート番号の指定
while (true) {
// コネクション確立を待ってブロックする.確立するとSocketインスタンスを返す
try (Socket socket = server.accept()) {
Expand Down Expand Up @@ -107,7 +108,7 @@ private void handleGet(BufferedReader reader, PrintWriter writer, String path) {
}

public static void main(String[] args) {
System.out.println("open http://localhost:8000/ with your browser!");
System.out.printf("open http://localhost:%d/ with your browser!\n", SERVER_PORT);
new WebServer();
}
}
6 changes: 4 additions & 2 deletions JavaScript/webserver.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
// このプログラムでは低レベルの処理を見せるために"net"モジュールを使っている
const net = require("net");

const SERVER_PORT = 8888;

function main() {
const server = net.createServer(); // サーバの作成
// JavaScriptでは基本的にイベントベースで処理を記述する
Expand All @@ -21,8 +23,8 @@ function main() {
server.on("connection", conn => {
handleClient(conn);
});
server.listen(8000); // コネクションの待ち受けを開始する
console.log("open http://localhost:8000/ with your browser!");
server.listen(SERVER_PORT); // コネクションの待ち受けを開始する
console.log(`open http://localhost:${SERVER_PORT}/ with your browser!`);
// ここでmain関数は終わるが,裏でコネクションの確立を待っている
}

Expand Down
10 changes: 6 additions & 4 deletions Python/webserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,16 @@

import socket
import threading
import typing
import io

SERVER_PORT=8888

def main():
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_sock.bind(('', 8000))
server_sock.bind(('', SERVER_PORT))
server_sock.listen(5)
print("open http://localhost:8000/ with your browser!")
print(f"open http://localhost:{SERVER_PORT}/ with your browser!")

while True:
client_sock, address = server_sock.accept()
Expand Down Expand Up @@ -60,7 +62,7 @@ def handle_client(client_sock: socket.socket):
print(f"unsupported method {method}")
f.write("HTTP/1.0 501 Not Implemented\r\n")

def handle_get(f: typing.TextIO, path: str):
def handle_get(f: io.TextIOWrapper, path: str):
""" GET要求を処理する """
if path == "/":
s = """\
Expand Down
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
# tiny-web-servers

This repository contains implementations of tiny web servers written in C, C#, Elixir, Go, Java, JavaScript (on Node.js), Python, and Ruby. All implementations have the same functionality.
This repository contains implementations of tiny web servers written
in C, C#, Elixir, Go, Java, JavaScript (on Node.js), Python, and Ruby.
All implementations have the same functionality.

I wrote these to use as a material of network programming exercises in one of my lectures.
I wrote these to use as a material of network programming exercises in
one of my lectures.

Note that comments in the source code are in Japanese.

Expand Down
12 changes: 7 additions & 5 deletions Ruby/webserver.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@

require "socket"

SERVER_PORT = 8888

def main()
puts("open http://localhost:8000/ with your browser!")
server = TCPServer.new('0.0.0.0', 8000) # サーバソケットの生成
server = TCPServer.new('0.0.0.0', SERVER_PORT) # サーバソケットの生成
puts("open http://localhost:#{SERVER_PORT}/ with your browser!")
loop do
client_socket = server.accept # コネクション確立を待つ
# コネクションが確立したら,新しいスレッドを開始する
Expand Down Expand Up @@ -43,8 +45,8 @@ def handle_client(sock)
end

if headers.length == 0
puts("no header!")
return
puts("no header!")
return
end
req = headers[0].split(" ") # 先頭行を " " で分割する
if req.length != 3
Expand Down Expand Up @@ -84,7 +86,7 @@ def handle_get(sock, path)
<!DOCTYPE html>
<html>
<head><title>404 Not Found</title></head>
<head><title>404 Not Found</title></head>
<body>#{path} is not found</body>
</html>
EOS
Expand Down

0 comments on commit 73035d0

Please sign in to comment.