ERLEDIGT
NEIN
NEIN
ANTWORTEN
14
14
ZUGRIFFE
1071
1071
EMPFEHLEN
-
07.04.09 07:49 #1
- Registriert seit
- Jan 2009
- Beiträge
- 59
Hi,
ich bin am Programmieren eines Spiels,
und ich habe schon versucht, einen Chat für
mein Spiel zu programmieren,
ich hab im Internet schon viel gefunden, was mich trotzdem net weiterbrachte
lief aber nur leider als Applet bei mir auf Eclipse, so mit ner batch datei
nicht, also kann mir irgendjemand einen Chat schreiben
der auf JFrame Basis läuft?
Wer mir den Chat programmiert, kommt oben im Abspann vor,
ich weiß nähmlich gar nicht mehr weiter...

PS:
diese Irc chats laufen doch auf "Kanälen" glaub ich.
Es soll einfach nur ein JTextField oben sein, indem alle nachrichten auftauchen
dann ein JTextFíeld unten in das man einfüllen muss, und mit enter bestätigt
mehr net
den Channel soll man net ändern können, aber im Code festlegen können, danke
schon mal im Voraus, Developer_XY
-
07.04.09 10:08 #2
Hi,
hast du dazu mal ernsthaft mit Google gesucht?
Klick mal hier.
Der 4.Eintrag(]HTML-Version) ist eine Anleitung zu einem kompletten Chat und mit ein ganz klein bisschen Grips kannst du den auch vom Applet zu einem Stand-Alone-Programm umwandeln.
Desweiteren: http://www.tutorials.de/forum/java/2...erstellen.html
Ciao
DosCoderGeändert von DosCoder (07.04.09 um 10:10 Uhr)
Man kann mich für das verantwortlich machen, was ich hier schreibe, nicht für das, was andere verstehen.
Sollte ich mal Mist labern weist mich bitte darauf hin.
Ich freue mich über ein Danke, wenn ich helfen konnte!
-
07.04.09 11:43 #3
- Registriert seit
- Jan 2009
- Beiträge
- 59
danke,
das hab ich noch nicht gefunden
ja danke erstmal für deine schnelle antwort, aber könnte mir hier noch einer helfen?
Also
in diesem Tutorial, habe ich mal die COdes ausprobiert, es ist nur ein fehler im Code ich weiß nicht wie ich ihn beheben soll, kann mir einer helfen ? bitte
PHP-Code:import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class Client extends Panel implements Runnable
{
// Components for the visual display of the chat windowsprivate
TextField tf = new TextField();
private TextArea ta = new TextArea();
// The socket connecting us to the serverprivate
Socket socket;
// The streams we communicate to the server; these come
// from the socketprivate
DataOutputStream dout;
private DataInputStream din;
// Constructorpublic
Client( String host, int port ) {
// Set up the screen
setLayout( new BorderLayout() );
add( "North", tf );
add( "Center", ta );
// We want to receive messages when someone types a line
// and its return, using an anonymous class as
// a callback
tf.addActionListener( new ActionListener()
{
}
public void actionPerformed( ActionEvent e )
{
processMessage( e.getActionCommand() );
// Connect to the server
try
{
// Initiate the
socket = new Socket( "", 12 );
// We got a connection! Tell the world
System.out.println( "connected to "+socket );
// Let's grab the streams and create DataInput/Output streams
// from them
din = new DataInputStream( socket.getInputStream() );
dout = new DataOutputStream( socket.getOutputStream() );}
// Start a background thread for receiving messagesnew
catch( IOException ie )
{ System.out.println( ie ); }
}
// Gets called when the user types something
private void processMessage( String message )
{try
{
// Send it to the server
dout.writeUTF( message );
// Clear out text input field
tf.setText( "" );}
catch( IOException ie )
{ System.out.println( ie ); }}
// Background thread runs this: show messages from other window
public void run()
{
try {// Receive messages one-by-one, forever
while (true) {
// Get the next
String message = din.readUTF();
// Print it to our text
ta.append( message+"\n" );}}
catch( IOException ie ) { System.out.println( ie ); }
}
}
-
07.04.09 12:38 #4
Hi,
Beim Überfliegen des Codes sind mir typische Fehler aufgefallen, die nur passieren können wenn man Code kopiert.
.
Zum Beipiel ist das "public" vom Konstruktor in den Kommentar darüber gerutscht, wie alle anderen Modifzierer auch.
Oder ab der Zeile "tf.addActionListener( new ActionListener()" geht die Fomatierung und vor allem die Zeichensetzung den Bach runter! Vergleiche doch mal mit dem Tutorial wo welche Klammern gesetzt werden. Also wird daraus:
das hierCode java:1 2 3 4 5 6 7
tf.addActionListener( new ActionListener() { } public void actionPerformed( ActionEvent e ) { processMessage( e.getActionCommand() );
Und beim nächsten mal Bitte die Fehlermeldung posten!Code java:1 2 3 4 5
tf.addActionListener( new ActionListener(){ public void actionPerformed( ActionEvent e ) { processMessage( e.getActionCommand() ); } });
Ciao
DosCoder
PS: Wir sind hier im Java-Forum, bitte verwende java-Tags statt php-Tags.Geändert von DosCoder (07.04.09 um 12:41 Uhr)
Man kann mich für das verantwortlich machen, was ich hier schreibe, nicht für das, was andere verstehen.
Sollte ich mal Mist labern weist mich bitte darauf hin.
Ich freue mich über ein Danke, wenn ich helfen konnte!
-
07.04.09 15:13 #5
- Registriert seit
- Jan 2009
- Beiträge
- 59
ich bins nochmal, also im Code wird verlangt dass man die Host Adresse angibt,
natürlich muss man irgendwie die Host adresse von sich selbst angeben, bei nem Applet versuch konnte man schreiben, this.getHost
aber ich hab jetzt das Problem, dass es ein JFrame ist, kannst du mir da bitte helfen?
Damit das funktioniert?
Btite
Code Java:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
import java.io.*; import java.net.*; public class ServerThread extends Thread { // The Server that spawned usprivate Server server; // The Socket connected to our clientprivate Socket socket; // Constructor. public ServerThread( Server server, Socket socket ) {// Save the parameters this.server = server; this.socket = socket; // Start up the threadstart(); } // This runs in a separate thread when start() is called in the// constructor. public void run() { try { // Create a DataInputStream for communication; the client // is using a DataOutputStream to write to us DataInputStream din = new DataInputStream( socket.getInputStream() ); // Over and over, forever ... while (true) { // ... read the next message ... String message = din.readUTF(); // ... tell the world ... System.out.println( "Sending "+message ); // ... and have the server send it to all server.sendToAll( message ); } } catch( EOFException ie ) { // This doesn't need an error message } catch( IOException ie ) { // This does; tell the world! ie.printStackTrace();} finally { // The connection is closed for one reason or another, // so have the server dealing with it server.removeConnection( socket );} } }
In der folgenden Klasse ist die Main, da müsstest du mir helfen, wenn du willst, bitteCode Java:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
import java.io.*; import java.net.*; import java.util.*; public class Server { // The ServerSocket we'll use for accepting new connectionsprivate ServerSocket ss; // A mapping from sockets to DataOutputStreams. This will // help us avoid having to create a DataOutputStream each time // we want to write to a stream. private Hashtable outputStreams = new Hashtable(); // Constructor and while-accept loop all in one. public Server( int port ) throws IOException { // All we have to do is listen listen( port ); } private void listen( int port ) throws IOException { // Create the ss = new ServerSocket( port ); // Tell the world we're ready to go System.out.println( "Listening on "+ss ); // Keep accepting connections forever while (true) { // Grab the next incoming Socket s = ss.accept(); // Tell the world we've got it System.out.println( "Connection from "+s ); // Create a DataOutputStream for writing data to the // other side DataOutputStream dout = new DataOutputStream( s.getOutputStream() ); // Save this stream so we don't need to make it again outputStreams.put( s, dout ); // Create a new thread for this connection, and then forget // about it new ServerThread( this, s ); } } // Get an enumeration of all the OutputStreams, one for each client // connected to usEnumeration Enumeration getOutputStreams() { return outputStreams.elements(); } // Send a message to all clients (utility routine) void sendToAll( String message ) { // We synchronize on this because another thread might be // calling removeConnection() and this would screw us up // as we tried to walk through the listsynchronized( outputStreams ) { // For each client ... for (Enumeration e = getOutputStreams(); e.hasMoreElements(); ) { // ... get the output stream ... DataOutputStream dout = (DataOutputStream)e.nextElement(); // ... and send the message try {dout.writeUTF( message );} catch( IOException ie ) { System.out.println( ie ); }}} // Remove a socket, and it's corresponding output stream, from our // list. This is usually called by a connection thread that has // discovered that the connectin to the client is dead. void removeConnection( Socket s ) { // Synchronize so we don't mess up sendToAll() while it walks // down the list of all output streamsa synchronized( outputStreams ) { // Tell the world System.out.println( "Removing connection to "+s ); // Remove it from our hashtable/list outputStreams.remove( s ); // Make sure it's closed try {s.close();} catch( IOException ie ) {System.out.println( "Error closing "+s ); ie.printStackTrace();}}} // Main routine//Usage: java Server <port> static public void main( String args[] ) throws Exception {// Get the port # from the command line int port = Integer.parseInt( args[0] ); // Create a Server object, which will automatically begin// accepting new Server( port );} }
Code Java:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
import java.awt.BorderLayout; import java.awt.TextArea; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import javax.swing.JFrame; public class Client extends JFrame implements Runnable { // Components for the visual display of the chat windowsprivate TextField tf = new TextField(); private final TextArea ta = new TextArea(); // The socket connecting us to the serverprivate Socket socket; // The streams we communicate to the server; these come // from the socketprivate DataOutputStream dout; protected DataInputStream din; // Constructorpublic public Client(final String host, final int port) { // Set up the screen setLayout(new BorderLayout()); setVisible(true); setSize(200,200); add("North", this.tf); add("Center", this.ta); // We want to receive messages when someone types a line // and its return, using an anonymous class as // a callback this.tf.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { processMessage(e.getActionCommand()); // Connect to the server try { // Initiate the Client.this.socket = new Socket("", 12); // We got a connection! Tell the world System.out.println("connected to " + Client.this.socket); // Let's grab the streams and create DataInput/Output // streams // from them Client.this.din = new DataInputStream(Client.this.socket.getInputStream()); Client.this.dout = new DataOutputStream(Client.this.socket.getOutputStream()); } // Start a background thread for receiving messagesnew catch (final IOException ie) { System.out.println(ie); } } }); } // Gets called when the user types something protected void processMessage(final String message) { try { // Send it to the server this.dout.writeUTF(message); // Clear out text input field this.tf.setText(""); } catch (final IOException ie) { System.out.println(ie); } } // Background thread runs this: show messages from other window public void run() { try {// Receive messages one-by-one, forever while (true) { // Get the next final String message = this.din.readUTF(); // Print it to our text this.ta.append(message + "\n"); } } catch (final IOException ie) { System.out.println(ie); } } public static void main(String[]args) { new Client("s",2);//<--Hier weiß ich nicht weiter, bitte, helf mir } }
-
07.04.09 20:55 #6
Hi,
Die gefragte Hostadresse ist nicht die IP-Adresse des Clienten, sondern die IP-Adresse des Computers auf dem dein Server läuft.
Was du machen willst (zum Testen) ist, den Server und den Klient (2 verschiedene Programme) auf der selben Maschine laufen zu lassen. Die IP "127.0.0.1" verweist immer auf den eigenen PC(=localhost).
Wenn dein Chat/Spiel fertig ist, dann hast du 2 Möglichkeiten, den Server laufen zu lassen:
1. Den Server auf beliebigem PC laufen lassen(z.B.: deinem Eigenen). Diese Variante hat aber Nachteile: Du musst deinen Mitspielern immer deine IP sagen, die sich ja regelmäßig ändert. Deine Freunde geben die dann in Eingabefeld ein, bevor Verbinung zum Server aufgenommen wird. Außerdem wir dein privater Pc nicht rund um die Uhr laufen, dass heißt, der Chat ist nur zu bestimmten Zeiten erreichbar.
2. Du suchst dir nen Webserver, der Servlets ausführt. Dieser läuft dann rund um die Uhr und ist immer erreichbar. Außerdem hast du einen Domainnamen als Host, die IP-Adresse brauchst du nicht, da der Domainname immer gleich ist. Der Nachteil: Es kostet Geld.
Wenn du noch weitere Fragen hast, nur zu.
Ciao
DosCoder
//Edit:
Desweiteren ist mir aufgefallen, dass in deinem Client immer noch ein fataler Fehler ist!
Oben habe ich dir doch den korrekten Code hingeschrieben! Das "ConnectionToTheServer"-Zeugs kommt DANACH und wird nicht irgendwie in actionPerformed reingebastelt (Siehe Tutorial, Client.java). Aber jetzt kann ich dich mal testen: Was passiert bei dem jetzigen Code?Geändert von DosCoder (07.04.09 um 22:22 Uhr)
Man kann mich für das verantwortlich machen, was ich hier schreibe, nicht für das, was andere verstehen.
Sollte ich mal Mist labern weist mich bitte darauf hin.
Ich freue mich über ein Danke, wenn ich helfen konnte!
-
08.04.09 07:16 #7
- Registriert seit
- Jan 2009
- Beiträge
- 59
was ich will ist dass, jeder in den Chat kommen soll, und der Chat selbst auf dem Port festgelegt ist,
Also ich weiß nicht, irgendwie muss es doch möglich sein, einen Chat zu schreiben,
du hattest gesagt der braucht einen Host, gehts nicht das jeder sein eigener Host ist,
und das Treffen in der Port adresse stattfindet?
Das wäre viel besser
ich habs auch schon ausprobiert,
diesen Port"127.0.0.1" anzugeben.
doch immer wenn ich beim "client" einen Text Eingebe und Bestätige kommt folgende FehlerMeldung
Ich denke mitlerweile hast du vielleicht auch den code, nur mal so,PHP-Code:Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Profi_Chat.Client.processMessage(Client.java:65)
at Profi_Chat.Client$1.actionPerformed(Client.java:38)
at java.awt.TextField.processActionEvent(Unknown Source)
at java.awt.TextField.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
ich hab die Zeilen nicht verändern, wie sie in meinem ersten Anfangs
Post schon gesendet wurde,
also was mache ich falsch, prinzipielle mach ich alles so wie du gesagt hast,
PS:
Wie macht man Java Code Tags hier in diesem Forum?
Code :1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
import java.awt.BorderLayout; import java.awt.TextArea; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import javax.swing.JFrame; public class Client extends JFrame implements Runnable { // Components for the visual display of the chat windowsprivate TextField tf = new TextField(); private final TextArea ta = new TextArea(); // The socket connecting us to the serverprivate Socket socket; // The streams we communicate to the server; these come // from the socketprivate DataOutputStream dout; protected DataInputStream din; // Constructorpublic public Client(final String host, final int port) { // Set up the screen setLayout(new BorderLayout()); setVisible(true); setSize(200,200); add("North", this.tf); add("Center", this.ta); // We want to receive messages when someone types a line // and its return, using an anonymous class as // a callback this.tf.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { processMessage(e.getActionCommand()); // Connect to the server try { // Initiate the Client.this.socket = new Socket("", 12); // We got a connection! Tell the world System.out.println("connected to " + Client.this.socket); // Let's grab the streams and create DataInput/Output // streams // from them Client.this.din = new DataInputStream(Client.this.socket.getInputStream()); Client.this.dout = new DataOutputStream(Client.this.socket.getOutputStream()); } // Start a background thread for receiving messagesnew catch (final IOException ie) { System.out.println(ie); } } }); } // Gets called when the user types something protected void processMessage(final String message) { try { // Send it to the server this.dout.writeUTF(message); // Clear out text input field this.tf.setText(""); } catch (final IOException ie) { System.out.println(ie); } } // Background thread runs this: show messages from other window public void run() { try {// Receive messages one-by-one, forever while (true) { // Get the next final String message = this.din.readUTF(); // Print it to our text this.ta.append(message + "\n"); } } catch (final IOException ie) { System.out.println(ie); } } public static void main(String[]args) { new Client("127.0.0.1",2); } }
Ich hab nicht ganz verstanden was du mit fatalem Fehler meinst,
könntest du mir in deinem nächsten Post als letztes bitte den richtigen Code
senden
-
08.04.09 11:34 #8
Hi,
deine NullpointerException kommt genau von diesem fatalen Error. Da dein Code zum Verbinden mit dem Server in der Methode actionPerformed() steht, wird er erst ausgeführt, wenn auf den Button "Senden" gedrückt wurde. Da aber die Methode processManage vor dem Serverzeugs aufgerufen wird, wird versucht, in einen OutputStream zu schreiben, der noch gar nicht initilaisiert wurde! Gehe deinen Code doch mal mit dem Debugger durch, ich nehme an, Eclipse besitzt so was(ich bin Netbeaner). Im Tutorial steht der richtige Client-Code.
Falls du es noch nicht verstanden hast: Server.java und Client.java sind 2 verschiedene Programme, die im reelen Leben auf verschiedenen Maschinen laufen.
Und nun zu den Hosts und Ports, ich versuche nochmal, es dir zu erkären.
Jeder PC hat eine IP. Wenn ein PC mit einem anderen Kontakt aufnehmen will. braucht er dessen ID. Dein Klient will sich mit dem PC verbinden, auf dem dein Server läuft, folglich braucht er dessen
ID. Der Server braucht zum Verbinden nicht die IP-Adresse des Klienten, warum später. Der Port ist nichts anderes, als die "Hausnummer auf dem PC, auf dem dein Server läuft.
Vergleich:
Du bist das Server-Programm, und wohnst in einem Haus in der Straße "192.89.0.1" mit der Hausnummer 4966. Wenn dir dein Freund(=Klient) jetzt einen Brief schreiben will, dann muss er deine Straße und deine Hausnummer wissen. Willst du IHM danach einen Brief schreiben, hast du ja seine Daten, da sie als Absender auf dem Brief stehen. Wenn du mehrere Freunde hast , können sie dir alle mit dir Verbindung aufnehmen. Schreibt jetzt einer eine Nachricht(=Brief), dann leitest du ihn einfach an alle Freunde weiter, die mit dir Verbindung aufgenommen haben.
Laufen/Läuft jetzt (ein Teil) dein/e/r Klienten auf dem selben PC wie das Server-Programm, müssen sie als als Adresse des Servers "127.0.0.1" angeben, der Port bleibt gleich.
Den Port deines Servers kannst du frei wählen, allerdings solltest du von den Portnummern bis 1023 Abstand nehmen, auf diesen laufen nämlich bekannte Dienste wie HTTP(Port 80), POP3 oder SMTP. Diese Dienste nennt man Well-Known-Services.
Ab 1023 bis 65535 sollten alle Ports frei sein, allerdings kann es immer passieren, dass ein anderer Hobbyprogrammierer zufällig denselben Port wie du benutzt.
Folgender Absatz ist keinesfalls als persölicher Angriff zu werten:
In dem Verlauf unseres "Gepräches" habe ich festgestellt, dass du mit GUI-Code wohl noch nicht so vertraut bist, insbesondere actionListener & Co. Hättest du gewusst, was der Code genau macht, hättest du von Anfang an die Klammern richtig gesetzt, anstatt sie irgendwie zu setzen, sodass kein Compilierfehler mehr aufaucht.
Was ich damit sagen möchte ist: Wenn du dich mit diesen anoymen Klassen noch nicht auskennst, ist es dann klug, sich mit einem Chat zu versuchen? Das musst du entscheiden, ich werde dir gerne weiterhelfen. Es geht hier einzig alleine um dich.
Ciao
DosCoderMan kann mich für das verantwortlich machen, was ich hier schreibe, nicht für das, was andere verstehen.
Sollte ich mal Mist labern weist mich bitte darauf hin.
Ich freue mich über ein Danke, wenn ich helfen konnte!
-
08.04.09 12:41 #9
- Registriert seit
- Jan 2009
- Beiträge
- 59
Man danke, dass du s mir mit dem Beispiel der Hausnummer erklärt hast, das habe ich wirklich nicht gewusst.
Auch dass Client und das andere 2 verschiedene Klassen sind habe ich noch nicht gewusst, also erstmal danke dazu.
Also nein, ich bin nicht vertraut mit dem umgang von anonymen Klassen, ich danke dir für deine Hilfe, wirklich, ohne dich hätte ich das nie kapiert.
Eine ganz entscheidende Frage habe ich da aber noch, bitte, ist die Klasse Server
auch eine Art Chat die über die Eingabeaufforderung läuft?
also nur mal , die Server Klasse hat eine main(),
in der, der Server gestartet wird,
dann kommt folgendes System.out.println""
Und dann kann man Dinge eingebenPHP-Code:Listening on ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=2]
ich glaube aber, dass das funktioniert, aber auf meinem Rechner,
weil da ist keine addr= und kein port=
nur der local port
wie könnte ich z.B. mit einem Anderen Chatten auf meinem Rechner, mit meiner "ID".
Wie könnte ich dem meine geben?
-
08.04.09 12:50 #10
Hi,
Ich würde eher sagen, die Klasse Chat verwaltet die Klienten, man kann ja im Server-Programm selbst nichts eingeben. Das Serverprogramm läuft als Konsole wartet einfach auf Anfragen von Klienten.
Außerdem:
Das Client und Server verschiedene Klassen sind, müsstest du gewusst haben, du hast mir ja im 6.Post die Klassen getrennt voneinander gepostet. Ich glaube, für dich war neu, dass die Server und Client 2 verschiedene Programme sind.Auch dass Client und das andere 2 verschiedene Klassen sind habe ich noch nicht gewusst, also erstmal danke dazu.
Antwort zu deinem neuem Beitrag
(Local)Port 2 ist schlecht, da, wie in meinem letzten Post gesagt, man nur Ports über 1023 verwenden sollte. Also bitte ändere den Port.
Nun zu deiner IP-Frage. Genau das ist das Problem bei diesem Chat, aber ich habe dir ja in Post 7 schon die Möglichkeiten genannt.
Ciao
DosCoder
PS: Kieg ich noch ein Renomme?Geändert von DosCoder (08.04.09 um 13:03 Uhr)
Man kann mich für das verantwortlich machen, was ich hier schreibe, nicht für das, was andere verstehen.
Sollte ich mal Mist labern weist mich bitte darauf hin.
Ich freue mich über ein Danke, wenn ich helfen konnte!
-
08.04.09 18:32 #11
- Registriert seit
- Jan 2009
- Beiträge
- 59
Ja, wenn du mir bitte einen gefallen tun könntest.
Kannst du mir eine Klasse namens "Chat.java" schreiben, die diese 3 Klassen verwendet bitte, dann geb ich dir mehr als einen Renomee
-
08.04.09 20:48 #12
Hi,
Kerl, war denn alles umsonst? Es kann keine Klasse Chat.java geben, da der Server(2 Klassen) und der Klient(1 Klasse) bis zu einem gewissen Grad unabhängig voneinerander sind, das heißt, dass es 2 verschiedene Programme sind. Wenn du jemanden haben willst, der den Code aus diesem PDF-Tutorial abschreibt, dann bitte ins Forum für unentgeltliche Stellenangebote posten, ich werde ganz sicher kein Code abschreiben; Ich will nur anderen helfen.
Ciao
DosCoderMan kann mich für das verantwortlich machen, was ich hier schreibe, nicht für das, was andere verstehen.
Sollte ich mal Mist labern weist mich bitte darauf hin.
Ich freue mich über ein Danke, wenn ich helfen konnte!
-
09.04.09 08:01 #13
- Registriert seit
- Jan 2009
- Beiträge
- 59
dieser Chat, den du mir gezeigt hast, läuft bei mir auf Eclipse nicht. Egal ich hab nen anderen aber dazu brauch ich deine Hilfe. Also, Applets kann man nicht mit der Eingabeaufforderung starten, wenn ja wie?
Mein Code sieht wie folgt aus, 3 Klassen, ein Applet:
Code :1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
import java.net.*; import java.io.*; class connection extends Thread { protected Socket client; protected DataInputStream in; protected PrintStream out; protected chatserver server; public connection(chatserver server, Socket client) { this.server=server; this.client=client; try { in = new DataInputStream(client.getInputStream()); out = new PrintStream(client.getOutputStream()); } catch (IOException e) { try { client.close(); } catch (IOException e2) {} ; System.err.println("Fehler beim Erzeugen der Streams: " + e); return; } this.start(); } public void run() { String line; try { while(true) { line=in.readLine(); if(line!=null) server.broadcast(line); } } catch (IOException e) { System.out.println("Fehler:" + e); } } }Code :1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
import java.net.*; import java.io.*; import java.util.*; public class chatserver implements Runnable { public static final int PORT = 1; protected ServerSocket listen; protected Vector connections; Thread connect; public chatserver() { try { listen = new ServerSocket(PORT); } catch (IOException e) { System.err.println("Fehler beim Erzeugen der Sockets:"+e); System.exit(1); } connections = new Vector(); connect = new Thread(this); connect.start(); } public void run() { try { while(true) { Socket client=listen.accept(); connection c = new connection(this, client); connections.addElement(c); } } catch (IOException e) { System.err.println("Fehler beim Warten auf Verbindungen:"+e); System.exit(1); } } public static void main(String[] args) { new chatserver(); } public void broadcast(String msg) { int i; connection you; for (i=0; i<connections.size(); i++) { you = (connection) connections.elementAt(i); you.out.println(msg); } } }Ich ´weiß, die Klasse help brauchst du jetzt aber nicht,Code :1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
import java.applet.Applet; import java.applet.AppletContext; import java.applet.AppletStub; import java.applet.AudioClip; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Event; import java.awt.Font; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Image; import java.awt.TextArea; import java.awt.TextField; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.net.MalformedURLException; import java.net.Socket; import java.net.URL; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import javax.sound.sampled.AudioFormat.Encoding; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JTextArea; import com.sun.j3d.utils.applet.MainFrame; public class JavaChat_1 extends Applet implements Runnable { public static final int PORT = 1; Socket socket; DataInputStream in; PrintStream out; TextField inputfield; TextArea outputarea; Thread thread; private static final long serialVersionUID = 4881953554409778241L; private final HashMap<String, InputStream> appStreams = new HashMap<String, InputStream>(); private final HashMap<String, String> appParams = new HashMap<String, String>(); String name; public JavaChat_1() { File f = new File("F:/FUTUR.PROGRAMS/Chat/Saves.txt"); name = getContents(f); new chatserver(); inputfield = new TextField(); outputarea = new TextArea(); outputarea.setFont( new Font("Dialog", Font.PLAIN, 12)); outputarea.setEditable(false); this.setLayout(new BorderLayout()); this.add("South", inputfield); this.add("Center", outputarea); this.setBackground(Color.cyan); this.setForeground(Color.cyan); inputfield.setBackground(Color.black); outputarea.setBackground(Color.black); JMenuBar bar = new JMenuBar();bar.setBackground(Color.black);this.add(bar,BorderLayout.NORTH); JMenu m = new JMenu("Start");m.setForeground(Color.cyan);bar.add(m); JMenuItem i = new JMenuItem("Benutzternamen ändern");i.setForeground(Color.cyan);i.setBackground(Color.black);m.add(i); i.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent evt) { b1ActionPerformed(evt); } private void b1ActionPerformed(ActionEvent evt) { new MainFrame(new Correct(),200,250); } }); JMenuItem i1 = new JMenuItem("Beenden");i1.setForeground(Color.cyan);i1.setBackground(Color.black);m.add(i1); i1.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent evt) { b1ActionPerformed(evt); } private void b1ActionPerformed(ActionEvent evt) { System.exit(0); } }); JTextArea a = new JTextArea(); a.setText(" Java_Chat_1.0");a.setEnabled(false); bar.add(a);a.setBackground(Color.black); JMenu me = new JMenu("Hilfe"); me.setForeground(Color.cyan); bar.add(me); JMenuItem m1 = new JMenuItem("Hilfe aufrufen"); m1.setBackground(Color.black); m1.setForeground(Color.cyan); me.add(m1); m1.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent evt) { b1ActionPerformed(evt); } private void b1ActionPerformed(ActionEvent evt) { new MainFrame (new Help(),200,250); } }); } public void start() { try { socket = new Socket(this.getCodeBase().getHost(), PORT); in = new DataInputStream(socket.getInputStream()); out = new PrintStream(socket.getOutputStream()); } catch (IOException e) { this.showStatus(e.toString()); say("Verbindung zum Server fehlgeschlagen!"); } say(name+" ist der ChatSitzung im Port:"+PORT+" beigetreten."); if (thread == null) { thread = new Thread(this); thread.setPriority(Thread.MIN_PRIORITY); thread.start(); } } public void stop() { try { socket.close(); } catch (IOException e) { this.showStatus(e.toString()); } if ((thread !=null) && thread.isAlive()) { thread.stop(); thread = null; } } public void run() { String line; try { while(true) { line = in.readLine(); if(line!=null) outputarea.appendText(line+'\n' ); } } catch (IOException e) { say("Verbindung zum Server abgebrochen"); } } public boolean action(Event e, Object what) { if (e.target==inputfield) { String inp=(String)name+": "+ e.arg; out.println(inp); inputfield.setText(""); return true; } return false; } public void say(String msg) { outputarea.appendText("*** "+msg+" ***\n"); } static public String getContents(File aFile) { StringBuilder contents = new StringBuilder(); try { BufferedReader input = new BufferedReader(new FileReader(aFile)); try { String line = null; while (( line = input.readLine()) != null){ contents.append(line); } } finally { input.close(); } } catch (IOException ex){ ex.printStackTrace(); } return contents.toString(); } public static void main(String ... args) { final Frame f = new Frame("Hybrid Application Demo"); final JavaChat_1 applet = new JavaChat_1(); final Enumeration<Applet> appletEnum = new Enumeration<Applet>() { public boolean hasMoreElements() { return false; } public Applet nextElement() { return null; } }; final AppletContext context = new AppletContext() { public Applet getApplet(String name) { return null; // not in application mode } public Enumeration<Applet> getApplets() { return appletEnum; } public AudioClip getAudioClip(URL url) { try { final Clip clip = AudioSystem.getClip(); AudioInputStream ais = AudioSystem.getAudioInputStream(url); AudioFormat af = ais.getFormat(); if(Encoding.ALAW.equals(af.getEncoding()) || Encoding.ULAW.equals(af.getEncoding())) { af = new AudioFormat( Encoding.PCM_SIGNED, af.getSampleRate(), af.getSampleSizeInBits() * 2, af.getChannels(), af.getFrameSize() * 2, af.getFrameRate(), true ); ais = AudioSystem.getAudioInputStream(af, ais); } clip.open(ais); return new AudioClip() { public void loop() { clip.loop(-1); } public void play() { clip.start(); } public void stop() { clip.stop(); } }; } catch(LineUnavailableException e) { e.printStackTrace(); return null; } catch(IOException e) { e.printStackTrace(); return null; } catch (UnsupportedAudioFileException e) { e.printStackTrace(); return null; } } public Image getImage(URL url) { return Toolkit.getDefaultToolkit().getImage(url); } public InputStream getStream(String key) { return applet.appStreams.get(key); } public Iterator<String> getStreamKeys() { return applet.appStreams.keySet().iterator(); } public void setStream(String key, InputStream stream) throws IOException { if(key != null && key.length() > 0) { applet.appStreams.put(key, stream); } } public void showDocument(URL url) { // no effect } public void showDocument(URL url, String target) { // no effect } public void showStatus(String status) { // no effect } }; AppletStub stub = new AppletStub() { public void appletResize(int width, int height) { } public AppletContext getAppletContext() { return context; } public URL getCodeBase() { URL rc = JavaChat_1.class.getResource("HybridApplication.class"); return rc; } public URL getDocumentBase() { URL rc = JavaChat_1.class.getResource("HybridApplication.class"); if(rc.getProtocol().equalsIgnoreCase("jar")) { try { String tmp = rc.toString().substring(4, rc.toString().indexOf("!/")); tmp = rc.toString().replaceAll("jar:", "").replaceAll("file:/", "file://"); tmp = tmp.substring(0, tmp.lastIndexOf("!/")); rc = new URL(null, tmp); } catch(MalformedURLException e) { e.printStackTrace(); rc = null; } } return rc; } public String getParameter(String name) { return applet.appParams.get(name); } public boolean isActive() { return f.isActive(); } }; applet.setStub(stub); if(args != null && args.length > 0) { String[] pars; for(String arg : args) { pars = arg.split("="); if(pars.length == 1) pars = new String[] {pars[0], "true"}; applet.appParams.put(pars[0].toLowerCase(), pars[1]); } } f.setLayout(new GridLayout(1, 1, 0, 0)); String arg; int width, height; try { width = ((arg = applet.getParameter("width")) != null)? Integer.parseInt(arg) : 800; } catch(NumberFormatException e) { width = 800; } try { height = ((arg = applet.getParameter("height")) != null)? Integer.parseInt(arg) : 600; } catch(NumberFormatException e) { height = 600; } Dimension d = new Dimension(width, height); applet.setPreferredSize(d); applet.setSize(d); f.addWindowListener(new WindowListener() { public void windowActivated(WindowEvent e) { applet.start(); } public void windowClosed(WindowEvent e) { System.exit(0); } public void windowClosing(WindowEvent e) { applet.stop(); applet.destroy(); f.dispose(); } public void windowDeactivated(WindowEvent e) { applet.stop(); } public void windowDeiconified(WindowEvent e) { applet.start(); } public void windowIconified(WindowEvent e) { applet.stop(); } public void windowOpened(WindowEvent e) { } }); applet.init(); f.add(applet); f.pack(); f.setVisible(true); } }
kannst du mir sagen wie ich die Klasse Java_Chat_1 starten soll? per eingabeaufforderung?
Ich finds einfach net heraus
PS:
Kann das daran liegen, dass man applets nciht starten kann?
Per Eingabeaufforderung?
-
09.04.09 08:01 #14Maik Tutorials.de Gastzugang
-
09.04.09 19:28 #15
@Maik: Danke fürs Renommee, echt nett!
@Developer_Y:
Mit Eclipse kenne ich mich nicht aus: Aber: Google, dein Freund und Helfer: Hier ist die Lösung.
Wenn du das Applet unbedingt in der Konsole ausführen willst:
Im jdk-Verzeichnis "bin" gibt es ein Programm namens "appletviewer". Allerdings brauchst du dazu die HTML-Seite mit dem Applet. Da sich meine HTML-Kenntnisse aber auf ziehmlich geringen Nivaeu halten, kann ich dir in dieser Hinsicht nicht helfen
. Aber man kann ja googlen
.
Beispiel:
Code :1
DosCoder@linux-rdm0:~> [b]appletviewer myApplet.html[/b]
Ciao
DosCoderGeändert von DosCoder (09.04.09 um 19:39 Uhr)
Man kann mich für das verantwortlich machen, was ich hier schreibe, nicht für das, was andere verstehen.
Sollte ich mal Mist labern weist mich bitte darauf hin.
Ich freue mich über ein Danke, wenn ich helfen konnte!





Zitieren

Login





