# chat als applet umgeschrieben - unbekannter fehler :(



## Morphl (28. Dez 2009)

Hallöchen bin recht neu in der sprache - außer büchern und tutorials keine praxiserfahrung 

so zu meinem problem: hab im inet nen quellcode für nen einfacheres chatprogram gefunden - da ich vorhab ein java game über kurz oder lang als applet zu schreiben fand ich das recht interesant

das programm beruht auf progrämchen (server + client), wobei ich versucht habe den clienten als webapp zum laufen zu bringen

zu meinem problem:

unter netbeans startet auch das app, wenn ichs inne webseite einfüge lokal abspeichere und starte kommts nicht weiter als bis zum jinput dialogue - der output von ( chooseNick(); ) kommt nichtmehr im applet an 

der code:

server


```
package chatserver2;

import javax.swing.*;
import javax.swing.event.*;
import java.net.*;
import java.util.*;
import java.io.*;

public class ChatServer
{
	public static ChatServer server;
	public static int port = 2444;
	public static ServerSocket serverSocket;
	public static Socket temp;
	public static ArrayList<User> users = new ArrayList<User>();
	public ChatServer(int ePort)
	{
		port = ePort;
		try{
			serverSocket = new ServerSocket(port);
			System.out.println("Server opened on port: " + port);
		}catch(Exception e){
			System.out.println("Server Port in use. Please choose another port.");
			System.exit(1);
		}
	}
	public static void main(String args[])
	{
		server = new ChatServer(Integer.parseInt(JOptionPane.showInputDialog("Enter the port #")));
		Thread mainLoop = new Thread(new Runnable()
		{
			public void run()
			{
				while(true)
				{
					try{
						temp = serverSocket.accept();
					} catch(Exception e){}
					User user = new User("nameless",temp);
					users.add(user);
					System.out.println("A new user has connected to the server.");
					Thread t = new Thread(new Runnable()
					{
						public void run()
						{
							Socket temp2 = temp;
							boolean stop = false;
							while(!stop)
							{
								String msg = "poop";
								try {
									msg = users.get(findUser(temp2)).getIn().readLine();
								} catch(SocketException e) {
									System.out.println(users.get(findUser(temp2)).getName() 
+ " has disconnected from the server.");
									sendAll(users.get(findUser(temp2)).getName() 
+ " has disconnected from the server.");
									users.remove(findUser(temp2));
									stop = true;
									break;
								}
								catch(IOException e){}
								if(msg.startsWith("/"))
								{
									if(msg.startsWith("/nick"))
									{
										String[] MSG = msg.split(" ");
										boolean found = false;
										for(int x = 0; x < users.size(); x++)
										{
											if(users.get(x).getName().equalsIgnoreCase(MSG[1]))
											{
												users.get(findUser(temp2)).getOut()
.println("Nickname is already in use.");
												found = true;
											}
										}
										if(!found)
										{
											sendAll(users.get(findUser(temp2)).getName() 
+ " is now known as " + MSG[1]);
											users.get(findUser(temp2)).changeNick(MSG[1]);
										}
									}
								}
								else
								{
									sendAll(msg,users.get(findUser(temp2)).getName());
								}
							}
						}
					});
					t.start();
				}
			}
		});
		mainLoop.start();
	}

	public static int findUser(Socket temp)
	{
		for(int x = 0; x < users.size(); x++)
		{
			if(users.get(x).getSocket() == temp)
			{
				return x;
			}
		}
		return -1;
	}


	public static int findUserByName(String name)
	{
		for(int x = 0; x < users.size(); x++)
		{
			if(users.get(x).getName().equalsIgnoreCase(name))
			{
				return x;
			}
		}
		return -1;
	}

	public static void sendAll(String msg, String name)
	{
		for(int x = 0; x < users.size(); x++)
		{
			users.get(x).getOut().println(name + ":" + msg);
		}
	}

	public static void sendAll(String msg)
	{
		for(int x = 0; x < users.size(); x++)
		{
			users.get(x).getOut().println(msg);
		}
	}
}

class User
{
	public String username;
	public PrintWriter out;
	public BufferedReader in;
	public Socket userSocket;
	public User(String Eusername, Socket EuserSocket)
	{
		username = Eusername;
		userSocket = EuserSocket;
		try {
			out = new PrintWriter(userSocket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(userSocket.getInputStream()));
		} catch(Exception e){}
	}

	public PrintWriter getOut()
	{
		return out;
	}

	public BufferedReader getIn()
	{
		return in;
	}

	public String getName()
	{
		return username;
	}

	public Socket getSocket()
	{
		return userSocket;
	}

	public void changeNick(String newstring)
	{
		username = newstring;
	}
}
```

der client:


```
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;

public class Oo extends JApplet implements ActionListener
{
	public int port;
	public String host;
	public String msg;
	public PrintWriter out;
	public BufferedReader in;
	public JTextArea messages;
	public JPanel displayPanel, sendPanel;
	public JFrame main;
	public JScrollPane messagePane;
	public JTextField sendM;
	public JButton send;

        	public void actionPerformed(ActionEvent e)
	{
		if(e.getSource() == send)
		{
			out.println(sendM.getText());
			sendM.setText("");
		}
		sendM.requestFocusInWindow();
	}

	public void displayMsg(String themsg)
	{
		messages.append("\n" +themsg);
	}

	public void chooseNick()
	{
		String k = JOptionPane.showInputDialog("Choose a nickname.");
		out.println("/nick " + k);
	}

    @Override
    public void init() {

        try {
			host = JOptionPane.showInputDialog("Enter the host name of the server.");
			port = Integer.parseInt(JOptionPane.showInputDialog("Enter the port #"));
			Socket connection = new Socket(host, port);
			System.out.println("Now connected to " + host + ".");
			out = new PrintWriter(connection.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

		} catch(Exception e) { e.printStackTrace(); }


		displayPanel = new JPanel();

		messages = new JTextArea(20,35);
		messages.setEditable(false);
		messagePane = new JScrollPane(messages);
		displayPanel.add(messagePane);

		sendM = new JTextField(18);
		sendM.addKeyListener(new KeyListenerImpl());

		send = new JButton("Send");
		send.addActionListener(this);

		sendPanel = new JPanel();
		sendPanel.add(sendM);
		sendPanel.add(send);

		getContentPane().add(displayPanel,BorderLayout.NORTH);
		getContentPane().add(sendPanel,BorderLayout.SOUTH);

		setVisible(true);
		sendM.requestFocusInWindow();

                Thread t = new Thread(new Runnable()
			{

		public void run()
				{
                    try {
                    displayMsg("You are now connected to host: " + host);
                    chooseNick();
                    String msg2 = null;
                    msg2 = in.readLine();
                    while (msg2 != null) {
                        displayMsg(msg2);
                        msg2 = in.readLine();
                    }
                    } catch (IOException ex) {
                    Logger.getLogger(Oo.class.getName()).log(Level.SEVERE, null, ex);
                }
                                        }
			});
			t.start();
    }
       



    private class KeyListenerImpl implements KeyListener {

        public KeyListenerImpl() {
        }

        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                send.doClick();
            }
        }

        public void keyReleased(KeyEvent e) {
        }

        public void keyTyped(KeyEvent e) {
        }
    }
}
```

würd mich über ne konstruktive erklärung freuen  (kann mir nur vorstellen das java durch sicherheitseinstellungen iwie die connection verbockt  )


----------



## SlaterB (28. Dez 2009)

> kann mir nur vorstellen das java durch sicherheitseinstellungen iwie die connection verbockt

du redest von Connection und Socket?
vielleicht hat es damit überhaupt nix zu tun, das kann man doch leicht prüfen,
entferne doch erstmal alles zu diesem Thema,

ob ein
JOptionPane.showInputDialog()
als Applet funktioniert, wage ich zu bezweifeln
(edit: obwohl, wenn du nur vom Output sprichst, dann funktioniert das vielleicht schon  )


----------



## Morphl (28. Dez 2009)

der input frame kommt


----------

