Server

mail@pastecode.io avatar
unknown
java
4 years ago
2.5 kB
1
Indexable
Never
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Serwer {

    private int port;
    private ServerSocket serverSocket;
    private Socket TCPconnectionWithClient;
    private BufferedWriter bw;
    private BufferedReader br;
    private InputStream is;


    Serwer(int port){
        this.port=port;
    }



    public static void main(String[] args) throws IOException {
        Serwer serwer = new Serwer(166);
        serwer.createServerSocket();
        serwer.startAcceptingRequests();
        serwer.gatherTCPconnectionStreams();
        serwer.readRequestFromClient();
        serwer.sendResponseToClient(serwer.bw, "Dzień dobry");


    }


    public static void log(String message){
        System.out.println("[S]" + message);
    }

    void createServerSocket() throws IOException {
        log("Server starts");
        log("Server socket creation");
        serverSocket = new ServerSocket(port);
        log("Server socket created");
    }

    void startAcceptingRequests() throws IOException {
        TCPconnectionWithClient = serverSocket.accept();
        log("Server accepts requests");
    }

    void gatherTCPconnectionStreams() throws IOException {
        log("Gathering streams");
        is = TCPconnectionWithClient.getInputStream();
        var outputStream = TCPconnectionWithClient.getOutputStream();
        var inputStreamReader = new InputStreamReader(is);
        var outputStreamWriter = new OutputStreamWriter(outputStream);
        br = new BufferedReader(inputStreamReader);
        bw = new BufferedWriter(outputStreamWriter);
        log("Streams gathered");
    }

    public void readRequestFromClient() throws IOException {
        StringBuilder result = new StringBuilder();
        char c;
        while((c=(char) is.read())!='\r')
            result.append(c);

        System.out.println(result.toString());
    }

    public void readRequestFromClient__DOESNTWORK() throws IOException {
        StringBuilder result = new StringBuilder();
        String line;
        while(!((line=br.readLine()).equals(""))){
            result.append(line);
        }

        System.out.println("line");
    }

    void sendResponseToClient(BufferedWriter bw, String response) throws IOException {
        bw.write(response+"\r\nEND");
        bw.flush();
        log("response sent");
    }
}