CLIENT

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

class Klient {

    private Socket socket;
    private BufferedReader br;
    private BufferedWriter bw;

    public static void main(String[] args) throws IOException {
        Klient client = new Klient("localhost", 166);
        client.sendRequestToServer(client.bw, "Witam");
        client.getStringResponseFromServer(client.br);


    }

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


    public static Socket createSocketConnectedToHost(String host, int port){
        try {
            return new Socket(host, port);
        }catch (IOException e){
            e.printStackTrace();
        }

        return null;
    }

    Klient(String hostname, int port){
        log("Client created");
        this.socket=createSocketConnectedToHost(hostname, port);
        log("TCP connection started");
        br=getBufferedReaderFromSocket(socket);
        bw=getBufferedWriterFromSocket(socket);
        log("Streams opened");
    }

    public BufferedWriter getBufferedWriterFromSocket(Socket client) {
        try
        {
            var s = client.getOutputStream();
            var ss = new OutputStreamWriter(s);
            return new BufferedWriter(ss);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public BufferedReader getBufferedReaderFromSocket(Socket client) {
        try
        {
            var s = client.getInputStream();
            var ss = new InputStreamReader(s);
            return new BufferedReader(ss);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void sendRequestToServer(BufferedWriter bw, String request) throws IOException {
        try {
            bw.write(request+"\r\n");
            bw.flush();
            log("request sent.");
        } catch (IOException e) {
            log("request not sent");
            e.printStackTrace();
        }

    }
    public String getStringResponseFromServer(BufferedReader bufferedReader) {
        StringBuilder response = new StringBuilder();
        try {
            String line;
            while (((line = bufferedReader.readLine()).equals("END"))) {
                response.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return response.toString();
    }


}