Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
6.2 kB
2
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 ServerSide extends JFrame{

    ServerSocket serverSide;
    Socket serverSocket;
    BufferedReader serverBuffer;
    PrintWriter serverOut;

        //Declare Component
        private JLabel serverHeading = new JLabel("Server Messenger");
        private JTextArea serverMessagTextArea = new JTextArea();
        private JTextField serverMessagTextFieldInput = new JTextField();
        private Font serverFont = new Font("Roboto",Font.PLAIN,20);

    // Constructor
    public ServerSide() {
        try {
            serverSide = new ServerSocket(7778);
            System.out.println("connection is ready to established");
            System.out.println("waiting");
            serverSocket = serverSide.accept();
            // for reading data
            serverBuffer = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
            // for writing data
            serverOut = new PrintWriter(serverSocket.getOutputStream());
            createServerGUI();
            handleServerEvents();
            startServerDataReading();
            // startServerDataWriting();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    private void handleServerEvents(){
        serverMessagTextFieldInput.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 serverContentToSend = serverMessagTextFieldInput.getText();
                    serverMessagTextArea.append("Me:"+serverContentToSend+"\n");
                    serverOut.println(serverContentToSend);
                    serverOut.flush();
                    serverMessagTextFieldInput.setText("");
                    serverMessagTextFieldInput.requestFocus();
                }
                
            }
            
        });
    }

    private void createServerGUI(){
        
        this.setTitle("Server");
        this.setSize(600,600);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //components code
        serverHeading.setFont(serverFont);
        serverMessagTextArea.setFont(serverFont);
        serverMessagTextFieldInput.setFont(serverFont);
        serverHeading.setIcon(new ImageIcon("chatlogo.png"));
        serverHeading.setHorizontalTextPosition(SwingConstants.CENTER);
        serverHeading.setVerticalTextPosition(SwingConstants.BOTTOM);
        serverHeading.setHorizontalAlignment(SwingConstants.CENTER);
        serverHeading.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
        serverMessagTextArea.setEditable(false);
        serverMessagTextFieldInput.setHorizontalAlignment(SwingConstants.CENTER);
        //frame layout
        this.setLayout(new BorderLayout());

        //adding components
        this.add(serverHeading,BorderLayout.NORTH);
        JScrollPane clientJScrollPane = new JScrollPane(serverMessagTextArea);
        this.add(clientJScrollPane,BorderLayout.CENTER);
        this.add(serverMessagTextFieldInput,BorderLayout.SOUTH);
        this.setVisible(true);
    }

    public void startServerDataReading() {
        // thread - will give data after reading
        Runnable serverRun1 = () -> {
            System.out.println("started reading");
            try {
                while (true) {

                    String message = serverBuffer.readLine();
                    if (message.equals("exit")) {
                        System.out.println("Client ended the chat");
                        JOptionPane.showMessageDialog(this, "Client ended the chat");
                        serverMessagTextFieldInput.setEnabled(false);
                        serverSocket.close();
                        break;
                    }
                    //System.out.println("Client : " + message);
                    serverMessagTextArea.append("Client : " + message+"\n");
                }
            } catch (Exception e) {
                //e.printStackTrace();
                System.out.println("connection is closed");
            }

        };
        new Thread(serverRun1).start();
    }

    public void startServerDataWriting() {
        System.out.println("started writing");
        // thread - will take data from user and will send to the client
        Runnable serverRun2 = () -> {
            try {
                while (!serverSocket.isClosed()) {

                    BufferedReader servBufferedReader = new BufferedReader(new InputStreamReader(System.in));
                    String serverContent = servBufferedReader.readLine();
                    serverOut.println(serverContent);
                    serverOut.flush();
                    if(serverContent.equals("exit")){
                        serverSocket.close();
                        break;
                    }
                }
                
            } catch (Exception e) {
                //e.printStackTrace();
                System.out.println("connection is closed");
            }
        };
        new Thread(serverRun2).start();
    }

    public static void main(String[] args) {
        System.out.println("this is server side..");
        new ServerSide();
    }
}