Skip to content

Commit

Permalink
Chapter.10 미션A 완료
Browse files Browse the repository at this point in the history
- Mission A: Threaded Server

Co-authored-by: famo1245 <kandallee38@gmail.com>
  • Loading branch information
csct3434 and famo1245 committed Dec 26, 2024
1 parent 5df82ae commit a4444e4
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 0 deletions.
45 changes: 45 additions & 0 deletions chapter10/missionA/Handler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package chapter10.missionA;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class Handler extends Thread {

private final Socket conn;

public Handler(Socket conn) {
this.conn = conn;
}

@Override
public void run() {
System.out.println("Connected to " + conn.getRemoteSocketAddress());

try (
Socket socket = conn;
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))
) {
String data;

while ((data = in.readLine()) != null) {
String responseMessage;

try {
int order = Integer.parseInt(data);
responseMessage = "Thank you for ordering " + order + " pizzas!\n";
} catch (NumberFormatException e) {
responseMessage = "Wrong number of pizzas, please try again\n";
}

System.out.println("Sending message to " + conn.getRemoteSocketAddress());
conn.getOutputStream().write(responseMessage.getBytes());
}
} catch (IOException e) {
System.err.println("Handler: " + e.getMessage());
}

System.out.println("Connection with " + conn.getRemoteSocketAddress() + " has been closed");
}
}
9 changes: 9 additions & 0 deletions chapter10/missionA/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package chapter10.missionA;

public class Main {

public static void main(String[] args) {
Server server = new Server();
server.start();
}
}
38 changes: 38 additions & 0 deletions chapter10/missionA/Server.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package chapter10.missionA;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

private static final int PORT = 12345;

private final ServerSocket serverSocket;

public Server() {
System.out.println("Starting up at: " + PORT);

try {
serverSocket = new ServerSocket(PORT);
} catch (IOException e) {
System.err.println("Server stopped.");
throw new RuntimeException(e);
}
}

public void start() {
System.out.println("Server listening for incoming connections");

while (true) {
try {
Socket conn = serverSocket.accept();
System.out.println("Client connection request from " + conn.getRemoteSocketAddress());
Thread thread = new Handler(conn);
thread.start();
} catch (IOException e) {
System.err.println("Server: " + e.getMessage());
}
}
}
}

0 comments on commit a4444e4

Please sign in to comment.