Приложение состоит из сервера и клиента. Когда я запускаю приложение локально с помощью ip (127.0.0.1), чат работает нормально. Конечно, все дело в том, чтобы запустить мессенджера на онлайн-сервере, чтобы я мог подключиться к нему с другого компьютера и быть полным гордости и радости.У меня есть Java-сервер и клиентская чат-программа, но где я могу ее загрузить?
Мой вопрос (и я знаю, что это звучит так, как будто я не проводил никаких исследований, и я ленивый ... поверьте мне, я озадачен) Что мне нужно сделать с программой и где я могу ее загрузить? ?
Я хочу получить доступ к своей программе из своей локальной сети, а не просто проверить ее на своем компьютере.
клиентское приложение:
package helloworldC;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class client extends JFrame {
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String serverIP;
private Socket connection;
//constructor
public client(String host){
super("Client");
serverIP = host;
userText= new JTextField();
userText.setEditable(false);
userText.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
sendMessage(event.getActionCommand());
userText.setText("");
}
}
);
add(userText, BorderLayout.NORTH);
chatWindow= new JTextArea();
add(new JScrollPane(chatWindow), BorderLayout.CENTER);
setSize(300,150);
setVisible(true);
}
//connect
public void startRunning(){
try{
connectToServer();
setupStreams();
whileChatting();
}catch(EOFException eofException){
showMessage("\n Client terminated") ;
}catch(IOException ioException){
ioException.printStackTrace();
}
finally{
closeCrap();
}
}
//conect to server
private void connectToServer() throws IOException{
showMessage("connecting...\n");
connection = new Socket(InetAddress.getByName(serverIP),6789);//52
showMessage("Connected to: " + connection.getInetAddress().getHostName());
}
// set up streams 53
private void setupStreams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n streams are ready");
}
//while chatting 54
private void whileChatting() throws IOException{
ableToType(true);
do{
try{
message = (String) input.readObject();
showMessage("\n"+message);
}catch(ClassNotFoundException classNotFoundException){
showMessage("\n class problen");
}
}while(!message.equals("SERVER -END"));
}
//close the streams and sockets
private void closeCrap(){
showMessage("\n closing sheet");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//send messages 56
private void sendMessage(String message){
try{
output.writeObject("CLIENT - "+ message);
output.flush();
showMessage("\nCLIENT -"+message);
}catch(IOException ioException){
chatWindow.append("\n something is wrong");
}
}
//update chatWindow57
private void showMessage(final String m){
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
chatWindow.append(m);
}
});
}
//permission to type
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
userText.setEditable(tof);
}
});
}
}
сервер:
package helloworld;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Server extends JFrame {
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
//constructor
public Server(){
super("Messenger");
userText=new JTextField();
userText.setEditable(false);
userText.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
sendMessage(event.getActionCommand());
userText.setText("");
}
}
);
add(userText, BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow));
setSize(300,150);
setVisible(true);
}
// set up and run the server
public void startRunning(){
try{
server = new ServerSocket(6789, 100);
while(true){
try{
//connect and have conversation
waitForConnection();
setupStreams();
whileChatting();
}catch(EOFException eofException){
showMessage("\n Server ended the connection! ");
}finally{
closeCrap();
}
}
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//wait for connection, then display connection information
private void waitForConnection() throws IOException {
showMessage("Waiting for connection...\n");
connection = server.accept();
showMessage("now connected to "+connection.getInetAddress().getHostName()+"\n");
}
//get stream to send and receive data
private void setupStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n Streams are good!\n");
}
//during the chat conversation
private void whileChatting() throws IOException{
String message = " You are now connected! ";
sendMessage(message);
ableToType(true);
do{
try{
message = (String) input.readObject();
showMessage("\n"+message);
}catch(ClassNotFoundException classNotFoundException){
showMessage("\n wtf???");
}
}while(!message.equals("CLIENT - END"));
}
// close streams and sockets
private void closeCrap(){
showMessage("\n Closing all...\n");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//send a message to client
private void sendMessage(String message){
try{
output.writeObject("SERVER - "+message);
output.flush();
showMessage("\nSERVER - " + message);
}catch(IOException ioException){
chatWindow.append("\n ERROR: cant send");
}
}
private void showMessage(final String text){
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
chatWindow.append(text);
}
}
);
}
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
userText.setEditable(tof);
}
}
);
}
}
Я бы порекомендовал простой облачный сервер или службу общего доступа, поддерживающую Java, причем последний вариант несколько редок. – kshikama
Amazon EC2 поддерживает это, я считаю. –