Witam!
Mam problem. Zrobiłem aplikację, prosty komunikator (już miałem z nim problem, rozwiązałem go z pomocą forumowiczów tutaj), i nie wiem jak ma uruchomić serwer, który jest w oddzielnej klasie, w oddzielnym pliku, z poziomu oddzielnej klasy. Ma ktoś pomysł jak to zrobić??
Czesc,
przede wszystkim mysle, ze powinienes jeszcze raz przestudiowac materialy dotyczace podstaw programowania zorientowanego obiektowo (OOP).
Natomiast jesli chodzi o pytanie, to, jesli jest tak jak mysle, to w swojej aplikacji (klasa definiujaca publiczna statyczna metode void main(String[])) musisz stworzyc nowy serwer (tj. obiekt Twojej klasy serwera), a potem przypuszczalnie wywolac metode, ktora ten serwer uruchamia (jesli sam konstruktor (!) tego nie robi).
Po pierwsze, przejrzałem sobie te materiały na Wikipedii. Po drugie klasa z serwerem nie jest definiującą publiczną statyczną z metodą main. Jak mam w takim razie uruchomić serwer? Załączam kod.
Server.java
package gaduła;
import gaduła.GadułaView.*;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JTextArea;
public class Server extends Thread
{
boolean working = true;
GadułaView m;
Server server;
recurse(GadułaView.new Connection();
Server(JTextArea ta)
{
m.area = ta;
}
void addText(String s)
{
m.area.setText(s+"\n");
}
public void end()
{
working = false;
}
public void run()
{
server.start();
while(working)
{
try
{
server = new Server(m.area);
server.start();
@SuppressWarnings("static-access")
ServerSocket s = new ServerSocket(m.PORT);
try
{
System.out.println("Oczekuje na rozmowe ...");
Socket socket = s.accept();
Connection c = new Connection(m.socket, m.area);
c.start();
System.out.println("Rozmowa przyjeta - trwa ! port: " + socket.getPort());
}
catch(Exception e)
{
}
}
catch(IOException e)
{
}
}
}
}
GadułaView.java
package gaduła;
import org.jdesktop.application.Action;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.io.Writer.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.ArrayList;
public class GadułaView extends FrameView {
boolean working = true;
InetAddress addr;
Socket socket;
boolean test;
PrintWriter out;
public static final int PORT = 80;
String ip;
Server server;
public void execute(String name) {
Class params[] = {Server.class};
// if you need parameters
//String[] args = new String[] { "Hello", "world" };
// Class params[] = new Class[] { args.getClass() });
try {
Class.forName(name).
getDeclaredMethod("main", params).
invoke(null, new Object[] {new String[] {}});
}
catch(Exception e){ e.printStackTrace();}
}
/*public class Server extends Thread
{
Server(JTextArea ta)
{
area = ta;
}
void addText(String s)
{
area.setText(s+"\n");
}
public void end()
{
working = false;
}
public void run()
{
server.start();
while(working)
{
try
{
server = new Server(area);
server.start();
ServerSocket s = new ServerSocket(PORT);
try
{
System.out.println("Oczekuje na rozmowe ...");
Socket socket = s.accept();
Connection c = new Connection(socket, area);
c.start();
System.out.println("Rozmowa przyjeta - trwa ! port: " + socket.getPort());
}
catch(Exception e)
{
}
}
catch(IOException e)
{
}
}
}
}
*/
public class Connection extends Thread{
Socket socket;
public JTextArea area;
Connection(Socket s, JTextArea ta)
{
socket = s;
area = ta;
}
void addText(String s)
{
area.setText(s + "\n" + pole.getText()+"\n");
java.awt.Toolkit.getDefaultToolkit().beep();
}
public void run()
{
try
{
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
while (true)
{
String str = in.readLine();
try {
if ( str.equals(java.util.ResourceBundle.getBundle("gaduła/resources/GadułaView").getString("END")))
{
System.out.println(java.util.ResourceBundle.getBundle("gaduła/resources/GadułaView").getString(" NADESZLO POLECENIE ZAMKNIECIA POŁĄCZENIA !"));
break;
}
this.addText(socket.getInetAddress() + java.util.ResourceBundle.getBundle("gaduła/resources/GadułaView").getString(" : ") + str);
}
catch(NullPointerException e)
{
out.print(e);
}
}
}
finally
{
System.out.println(java.util.ResourceBundle.getBundle("gaduła/resources/GadułaView").getString("POŁĄCZENIE ZOSTAŁO PRZERWANE ...."));
socket.close();
}
}
catch(IOException e)
{
przycisk2.setEnabled(false);
}
}
}
public GadułaView(SingleFrameApplication app) {
super(app);
initComponents();
}
@Action
public void showAboutBox() {
if (aboutBox == null) {
JFrame mainFrame = GadułaApp.getApplication().getMainFrame();
aboutBox = new GadułaAboutBox(mainFrame);
aboutBox.setLocationRelativeTo(mainFrame);
}
GadułaApp.getApplication().show(aboutBox);
}
@SuppressWarnings("unchecked")
//Generated Code
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
mainPanel = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
area = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
pole = new javax.swing.JTextField();
przycisk3 = new javax.swing.JButton();
przycisk = new javax.swing.JButton();
przycisk2 = new javax.swing.JButton();
menuBar = new javax.swing.JMenuBar();
javax.swing.JMenu fileMenu = new javax.swing.JMenu();
javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
javax.swing.JMenu helpMenu = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
mainPanel.setName("mainPanel"); // NOI18N
jScrollPane1.setName("jScrollPane1"); // NOI18N
area.setColumns(20);
area.setRows(5);
area.setName("area"); // NOI18N
jScrollPane1.setViewportView(area);
area.setEditable(false);
jScrollPane2.setName("jScrollPane2"); // NOI18N
jList1.setModel(new javax.swing.AbstractListModel() {
String[] strings = {"KONTAKTY (JESZCZE NIE DZIAŁA!!" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jList1.setName("jList1"); // NOI18N
jScrollPane2.setViewportView(jList1);
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(gaduła.GadułaApp.class).getContext().getResourceMap(GadułaView.class);
pole.setText(resourceMap.getString("pole.text")); // NOI18N
pole.setName("pole"); // NOI18N
przycisk3.setText(resourceMap.getString("przycisk3.text")); // NOI18N
przycisk3.setName("przycisk3"); // NOI18N
przycisk3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
wyslij(evt);
}
});
przycisk.setText(resourceMap.getString("przycisk.text")); // NOI18N
przycisk.setName("przycisk"); // NOI18N
przycisk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
rozlacz(evt);
}
});
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(gaduła.GadułaApp.class).getContext().getActionMap(GadułaView.class, this);
przycisk2.setAction(actionMap.get("sendInformation")); // NOI18N
przycisk2.setText(resourceMap.getString("przycisk2.text")); // NOI18N
przycisk2.setName("przycisk2"); // NOI18N
przycisk2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
polacz(evt);
}
});
javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pole, javax.swing.GroupLayout.DEFAULT_SIZE, 285, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 285, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(3, 3, 3))
.addGroup(mainPanelLayout.createSequentialGroup()
.addGap(36, 36, 36)
.addComponent(przycisk3, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(przycisk2)
.addGap(18, 18, 18)
.addComponent(przycisk, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
mainPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {przycisk, przycisk2, przycisk3});
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addGap(5, 5, 5)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(mainPanelLayout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pole, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane2))
.addGap(11, 11, 11)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(przycisk2)
.addComponent(przycisk)
.addComponent(przycisk3))
.addGap(92, 92, 92))
);
menuBar.setName("menuBar"); // NOI18N
fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
fileMenu.setName("fileMenu"); // NOI18N
exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
exitMenuItem.setText(resourceMap.getString("exitMenuItem.text")); // NOI18N
exitMenuItem.setName("exitMenuItem"); // NOI18N
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
helpMenu.setName("helpMenu"); // NOI18N
jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
jMenuItem1.setName("jMenuItem1"); // NOI18N
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
www(evt);
}
});
helpMenu.add(jMenuItem1);
aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
aboutMenuItem.setText(resourceMap.getString("aboutMenuItem.text")); // NOI18N
aboutMenuItem.setName("aboutMenuItem"); // NOI18N
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
setComponent(mainPanel);
setMenuBar(menuBar);
}// </editor-fold>
private void sendInformation()
{
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out= new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
out.println(pole.getText());
if(in == null){System.out.print("IN IS NULL"); }
area.setText("Ja:" + pole.getText()+"\n");
pole.setText("");
}
catch(IOException e)
{
System.out.println("Problem z wyslaniem informacji ...");
System.out.println(e);
}
}
private void www(java.awt.event.ActionEvent evt) {
if (java.awt.Desktop.isDesktopSupported()) {
java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
if (desktop.isSupported(java.awt.Desktop.Action.BROWSE)) {
try {
desktop.browse(new URI("http://www.szymekdo.cba.pl"));
}
catch (IOException e) {
System.out.println(e);
}
catch (URISyntaxException e) {
System.out.println(e);
}
}
}
else {
// // TODO add your handling code here:
}
}
private void wyslij(java.awt.event.ActionEvent evt) {
sendInformation();
}
private void polacz(java.awt.event.ActionEvent evt) {
String ip=pole.getText();
try
{
addr = InetAddress.getByName(ip);
System.out.println("=Lacze sie z komputerem o adresie : " + ip);
socket = new Socket(ip, PORT);
System.out.println("==Na porcie: " + socket.getPort());
test = true;
}
catch(Exception e)
{
przycisk2.setEnabled(true);
System.out.println(e);
test = false;
}
if (test){
przycisk.setEnabled(true);
przycisk2.setEnabled(false);
area.setText("");
}
else{
if(socket != null){
try {
socket.close();
} catch (IOException ex) {
System.out.print("Problem z zamknieciem socketu");
System.out.println(ex);
}
}
}
}
private void rozlacz(java.awt.event.ActionEvent evt) {
try {
socket.close();
} catch (IOException ex) {
System.out.print("Problem z zamknieciem socketu");
Logger.getLogger(GadułaView.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Variables declaration - do not modify
public javax.swing.JTextArea area;
private javax.swing.JList jList1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JPanel mainPanel;
private javax.swing.JMenuBar menuBar;
private javax.swing.JTextField pole;
private javax.swing.JButton przycisk;
private javax.swing.JButton przycisk2;
private javax.swing.JButton przycisk3;
// End of variables declaration
private JDialog aboutBox;
}
GadułaApp.java
/*
* GadułaApp.java
*/
package gaduła;
import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;
/**
* The main class of the application.
*/
public class GadułaApp extends SingleFrameApplication {
/**
* At startup create and show the main frame of the application.
*/
@Override protected void startup() {
show(new GadułaView(this));
}
/**
* This method is to initialize the specified window by injecting resources.
* Windows shown in our application come fully initialized from the GUI
* builder, so this additional configuration is not needed.
*/
@Override protected void configureWindow(java.awt.Window root) {
}
/**
* A convenient static getter for the application instance.
* @return the instance of GadułaApp
*/
public static GadułaApp getApplication() {
return Application.getInstance(GadułaApp.class);
}
/*
* Main method launching the application.
*/
public static void main(String[] args) {
launch(GadułaApp.class, args);
}
}
Poczytaj trochę (a jeszcze lepiej dużo) na temat Javy. Metodę main() masz w klasie AppGaduła, a ona jest w pakiecie gaduła. Musisz się znaleźć w nadkatalogu dla katalogu gaduła i wpisać
java gaduła.AppGaduła
Ale mi chodzi o uruchomienie serwera z poziomu klasy GadułaView. Znalazłem coś o metodzie launch ale nie mogę tego użyć.
Wykonywanie programu napisanego w Javie zaczyna się od metody public static void main(String[] args)
To wiem, ale gdy wstawiłem ta metodę do klasy Server, NetBeans wyrzuca mi, że non-static variable cannot be referenced from a static context, a gdy zrobię po prostu public void main itd. to mówi, że nie może znaleźć zmiennych, które są w oddzielnej klasie, albo illegal start of expression.
Ehh. Krótki wstęp do Javy:
w Javie de facto nie istnieje coś takiego jak program. Podstawowymi jednostkami wykonawczymi w Javie są klasy. zatem wywołanie polecenia java MojaKlasa
wywołuje metodę MojaKlasa.main(String[] args)
To że otrzymujesz komunikat non-static variable cannot be referenced from a static context
jest spowodowany tym że prawdopodobnie chcesz się odwołać do jakiegoś instancyjnego pola. Krótko mówiąc - metody statyczne mogą odwoływać się tylko do pól statycznych. Ogólnie muszę też cię chyba uświadomić że strasznie dziwnie zakodowałeś serwer - Server dziedziczy po wątku, posiada pole będące referencją do Servera a jego metoda run() działa tak, że pole jest inicjowane nowym Serverem a następnie startowany jest wątek i to wszystko rekurencyjnie.
Z takim rozwiązaniem dostaniesz na twarz albo OutOfMemoryError albo StackOverflowError (sam nie wiem co szybciej:)) Przemyśl jeszcze raz architekturę serwera i przede wszystkim wgryź się w temat wątków (zwłaszcza w różnicę między klasą Thread a interfejsem Runnable czy Callable)