dimanche 28 avril 2019

How do I put a Server class on my website so my Client class can communicate with it from different computers?

I have a server client application working just how I want it locally. I need to get the server online so the client program can be used from different computers. Not sure how to do this. I have my own website that I thought I could just put the Server on in the background.

Is this possible or am I just looking at this the wrong way.

Server.java

package core;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;



import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;

public class Server {

    public static void main(String[] args) throws IOException {

        ArrayList<ClientHandler> clients = new ArrayList<>();
        ServerSocket serverSocket = null;
        int clientNum = 1; // keeps track of how many clients were created

        // 1. CREATE A NEW SERVERSOCKET
        try {
            serverSocket = new ServerSocket(4444); // provide MYSERVICE at port
                                                    // 4444
        } catch (IOException e) {
            System.out.println("Could not listen on port: 4444");
            System.exit(-1);
        }

        // 2. LOOP FOREVER - SERVER IS ALWAYS WAITING TO PROVIDE SERVICE!
        while (true) {
            Socket clientSocket = null;
            try {

                // 2.1 WAIT FOR CLIENT TO TRY TO CONNECT TO SERVER
                System.out.println("Waiting for client " + clientNum + " to connect!");
                clientSocket = serverSocket.accept();
                clientNum++;
                ClientHandler c = new ClientHandler(clientSocket, clients);
                clients.add(c);
                // 2.2 SPAWN A THREAD TO HANDLE CLIENT REQUEST
                Thread t = new Thread(c);
                t.start();

            } catch (IOException e) {
                System.out.println("Accept failed: 4444");
                System.exit(-1);
            }

            // 2.3 GO BACK TO WAITING FOR OTHER CLIENTS
            // (While the thread that was created handles the connected client's
            // request)

        } // end while loop

    } // end of main method

} // end of class MyServer

class ClientHandler implements Runnable {
    Socket s; // this is socket on the server side that connects to the CLIENT
    ArrayList<ClientHandler> others;
    Scanner in;
    PrintWriter out;

    ClientHandler(Socket s, ArrayList<ClientHandler> others) throws IOException {
        this.s = s;
        this.others = others;
        in = new Scanner(s.getInputStream());
        out = new PrintWriter(s.getOutputStream());
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Runnable#run()
     */
    public void run() {
        // 1. USE THE SOCKET TO READ WHAT THE CLIENT IS SENDING
        while (true) {
            String clientMessage = in.nextLine();
            // System.out.println(clientMessage);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try (PrintWriter fileWriter = new PrintWriter(new FileOutputStream(new File("chat.txt"), true));) {
                        fileWriter.println(clientMessage);
                        fileWriter.close();
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    // System.out.println(others.size());
                    for (ClientHandler c : others) {
                        // System.out.println(c.toString());
                        c.sendMessage(clientMessage);
                    }

                }
            }).start();
        }
    }

    private void sendMessage(String str) {
        out.println(str);
        out.flush();
    }
} // end of class ClientHandler

ClientSide.java

package core;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;

/**
 * @author tywemc
 *
 */
public class ClientLogin extends JFrame {

    private JPanel contentPane;
    private JTextField textField;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ClientLogin frame = new ClientLogin();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public ClientLogin() {
        setTitle("Login Page");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 300, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        textField = new JTextField();
        textField.setBounds(59, 167, 171, 25);
        contentPane.add(textField);
        textField.setColumns(10);

        JLabel lblClient = new JLabel("Client");
        lblClient.setFont(new Font("Arial Black", Font.BOLD, 34));
        lblClient.setBounds(36, 35, 171, 54);
        contentPane.add(lblClient);

        JLabel loginLabel = new JLabel("Enter your name:");
        loginLabel.setFont(new Font("Times New Roman", Font.PLAIN, 22));
        loginLabel.setBounds(10, 118, 197, 38);
        contentPane.add(loginLabel);

        JButton btnLogin = new JButton("Login");
        btnLogin.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                ClientSide client = new ClientSide(textField.getText());
                client.setVisible(true);
            }

        });
        btnLogin.setFont(new Font("Tahoma", Font.PLAIN, 14));
        btnLogin.setBounds(83, 205, 89, 23);
        contentPane.add(btnLogin);
    }
}




Aucun commentaire:

Enregistrer un commentaire