Commit 30c1c112 authored by Ivan Dunko's avatar Ivan Dunko
Browse files

Added http server code

parent 719a2221
package ru.stryapkov.http.server;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.LinkedBlockingQueue;
public class ClientThread extends Thread{
private static final String page =
"<html>\n" +
"<body>\n" +
"<h1>Hello, World!</h1>\n" +
"</body>\n" +
"</html>";
private final LinkedBlockingQueue<Socket> clients;
private final int id;
ClientThread(LinkedBlockingQueue<Socket> clients, int id){
this.clients = clients;
this.id = id;
}
@Override
public void run(){
while (!Thread.interrupted()){
try {
System.out.println("ID: " + id);
Socket client = clients.take();
BufferedReader in = new BufferedReader(
new InputStreamReader(
client.getInputStream()
)
);
boolean isGet = false;
while (true){
String s = in.readLine();
if (s == null || s.trim().isEmpty())
break;
if (s.split(" ")[0].equals("GET"))
isGet = true;
//System.out.println(s);
}
if (isGet) {
String response = "HTTP/1.1 200 OK\n" +
"Server: myserver\n" +
"Content-Length: " + page.length() + "\n" +
"Content-Type: text/html\n" +
"Connection: Closed\r\n\r\n" + page;
client.getOutputStream().write(response.getBytes(StandardCharsets.UTF_8));
client.getOutputStream().flush();
}
client.close();
sleep(10000);
}
catch (Exception e){
return;
}
}
}
}
package ru.stryapkov.http.server;
import javafx.util.Pair;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
public class Server {
public static final int PORT = 10001;
public static final int THREAD_CNT = 3;
public static void main(String[] args){
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(PORT);
}
catch (IOException e){
e.printStackTrace();
return;
}
LinkedBlockingQueue<Socket> clients = new LinkedBlockingQueue<>();
ClientThread []clientThread = new ClientThread[THREAD_CNT];
for (int i = 0; i < THREAD_CNT; ++i) {
clientThread[i] = new ClientThread(clients, i);
clientThread[i].start();
}
while (true){
try {
Socket socket = serverSocket.accept();
clients.put(socket);
}
catch (Exception e){
e.printStackTrace();
return;
}
}
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment