Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
6.1 kB
3
Indexable
Never
import java.net.*;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;

public class ClientSide extends JFrame{

    Socket clientSocket;
    BufferedReader clientBuffer;
    PrintWriter clientOut;

    //Declare Component
    private JLabel clientHeading = new JLabel("Client Area");
    private JTextArea clientMessagTextArea = new JTextArea();
    private JTextField clientMessagTextFieldInput = new JTextField();
    private Font clientFont = new Font("Roboto",Font.PLAIN,20);


    public ClientSide() {
        try {
            System.out.println("sending request to server");
            clientSocket = new Socket("127.0.0.1", 7777);
            System.out.println("connection done");

            clientBuffer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            // for writing data
            clientOut = new PrintWriter(clientSocket.getOutputStream());
            createClientGUI();
            handleClientEvents();
            startClientDataReading();
            //startClientDataWriting();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handleClientEvents(){
        clientMessagTextFieldInput.addKeyListener(new KeyListener() {

            @Override
            public void keyTyped(KeyEvent e) {
                
            }

            @Override
            public void keyPressed(KeyEvent e) {
                
            }

            @Override
            public void keyReleased(KeyEvent e) {
                //System.out.println("Key Released "+e.getKeyCode()); 
                if(e.getKeyCode() == 10){
                    //System.out.println(("you have pressed enter button"));
                    String clientContentToSend = clientMessagTextFieldInput.getText();
                    clientMessagTextArea.append("Me:"+clientContentToSend+"\n");
                    clientOut.println(clientContentToSend);
                    clientOut.flush();
                    clientMessagTextFieldInput.setText("");
                    clientMessagTextFieldInput.requestFocus();
                }
                
            }
            
        });
    }

    private void createClientGUI(){
        this.setTitle("Client Messenger[END]");
        this.setSize(600,600);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //components code
        clientHeading.setFont(clientFont);
        clientMessagTextArea.setFont(clientFont);
        clientMessagTextFieldInput.setFont(clientFont);
        clientHeading.setIcon(new ImageIcon("chatlogo.png"));
        clientHeading.setHorizontalTextPosition(SwingConstants.CENTER);
        clientHeading.setVerticalTextPosition(SwingConstants.BOTTOM);
        clientHeading.setHorizontalAlignment(SwingConstants.CENTER);
        clientHeading.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
        clientMessagTextArea.setEditable(false);
        clientMessagTextFieldInput.setHorizontalAlignment(SwingConstants.CENTER);
        //frame layout
        this.setLayout(new BorderLayout());

        //adding components
        this.add(clientHeading,BorderLayout.NORTH);
        JScrollPane clientJScrollPane = new JScrollPane(clientMessagTextArea);
        this.add(clientJScrollPane,BorderLayout.CENTER);
        this.add(clientMessagTextFieldInput,BorderLayout.SOUTH);
        this.setVisible(true);
    }

    public void startClientDataReading() {
        // thread - will give data after reading
        Runnable ClientRun1 = () -> {
            System.out.println("reader started");
            try {
                while (!clientSocket.isClosed()) {

                    String message = clientBuffer.readLine();
                    if (message.equals("exit")) {
                        System.out.println("Server terminated the chat");
                        JOptionPane.showMessageDialog(this, "Server Terminated the chat");
                        clientMessagTextFieldInput.setEnabled(false);
                        clientSocket.close();
                        break;
                    }
                    //System.out.println("Server : " + message);
                    clientMessagTextArea.append("Server : " + message+"\n");
                }
            }catch (Exception e) {
                //e.printStackTrace();
                System.out.println("connection closed");
            }
        };
        new Thread(ClientRun1).start();
    }

    public void startClientDataWriting() {
        System.out.println("writer started");
        // thread - will take data from user and will send to the client
        Runnable ClientRun2 = () -> {
            try {
                while (true) {
                    BufferedReader ClientBufferedReader = new BufferedReader(new InputStreamReader(System.in));
                    String ClientContent = ClientBufferedReader.readLine();
                    clientOut.println(ClientContent);
                    clientOut.flush();
                    if(ClientContent.equals("exit")){
                        clientSocket.close();
                        break;
                    }
                }
                System.out.println("connection closed");
            } catch (Exception e) {
                e.printStackTrace();
                //System.out.println("connection closed");
            }
        };
        new Thread(ClientRun2).start();
    }

    public static void main(String[] args) {
        System.out.println("this is client..going to start client");
        new ClientSide();
    }
}