如何在我的网站上放置Server类,以便Client类可以从其他计算机与之通信?

时间:2019-04-28 21:53:16

标签: java web networking server client

我有一个服务器客户端应用程序,可以按照我在本地所需的方式工作。我需要使服务器联机,以便可以从其他计算机使用客户端程序。不确定如何执行此操作。我有自己的网站,我认为我可以将服务器放在后台。

这是可能的还是我只是以错误的方式看待这个问题。

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.JTextArea;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;

public class ClientSide extends JFrame {

    private JPanel contentPane;
    private JTextField textField;
    private String name;
    private JTextArea textArea;
    private Thread serverListener;
    private Socket socket;
    private Scanner in;
    private PrintWriter out;

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

    /**
     * Create the frame.
     * 
     * @throws IOException
     */
    public ClientSide(String myName) {
        try {
            socket = new Socket("localhost", 4444);
            in = new Scanner(socket.getInputStream());
            out = new PrintWriter(socket.getOutputStream());
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        serverListener = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    String clientMessage = in.nextLine();
                    try {
                        System.out.println("Receiving before dec: " + clientMessage);
                        clientMessage = Crypto.decrypt(clientMessage, "key");
                        System.out.println("Receiving after dec: " + clientMessage);
                        addLine(clientMessage);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        });
        serverListener.start();
        name = myName;
        setTitle("Client Side");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));

        JPanel topPanel = new JPanel();
        FlowLayout flowLayout = (FlowLayout) topPanel.getLayout();
        flowLayout.setAlignment(FlowLayout.LEFT);
        contentPane.add(topPanel);

        textArea = new JTextArea();
        textArea.setEditable(false);
        textArea.setColumns(20);
        textArea.setRows(7);
        topPanel.add(textArea);

        JPanel bottomPanel = new JPanel();
        contentPane.add(bottomPanel);
        bottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));

        JLabel lblMessage = new JLabel("Message");
        bottomPanel.add(lblMessage);

        textField = new JTextField();
        bottomPanel.add(textField);
        textField.setColumns(10);

        JButton btnSend = new JButton("Send");
        btnSend.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // send string/message to server
                String clientMessage;
                try {
                    clientMessage = Crypto.encrypt(name + ": > " + textField.getText(), "key");
                    System.out.println("Sending: " + clientMessage);
                    out.println(clientMessage);
                    out.flush();
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

            }

        });
        bottomPanel.add(btnSend);
    }

    public void addLine(String text) {
        textArea.setText(textArea.getText() + text + "\n");
    }

}

1 个答案:

答案 0 :(得分:0)

如果ClientSide类在端口4444上与服务器应用程序连接,则可以执行以下操作:

  1. 将您的客户端打包为jar文件,并在您要将其分发到的每台计算机上运行。
  2. 确保所有这些计算机都已安装JRE。 3将您的服务器模块打包为jar文件
  3. 您应该拥有服务器或具有管理权限。因此,如果不存在,则可以安装Java。 根据操作系统的不同,可能需要SSH技能
  4. 确保在主机服务器上启用PORT 4444。防火墙
  5. 获取服务器的公共IP地址,并在ClideSide代码中使用它。