import java.net.*;
import java.io.*;
import java.awt.*;
import java.applet.*;
import javax.swing.JOptionPane;
public class JavaChatClient extends Applet implements Runnable {
private static final long serialVersionUID = 1L;
public static final int PORT = 9999;
Socket socket;
DataInputStream in;
PrintStream out;
TextField inputfield;
TextArea outputarea;
Thread thread;
InetAddress ip = null;
int localport;
int localip;
boolean connect;
public void init() {
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.lightGray);
this.setForeground(Color.black);
inputfield.setBackground(Color.white);
outputarea.setBackground(Color.white);
}
@SuppressWarnings("deprecation")
public void start() {
try {
socket = new Socket(this.getCodeBase().getHost(), PORT);
ip = socket.getInetAddress();
localport = socket.getLocalPort();
in = new DataInputStream(socket.getInputStream());
out = new PrintStream(socket.getOutputStream());
say("Verbindung zum Server aufgenommen...");
connect = true;
if (thread == null) {
thread = new Thread(this);
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
}
} catch (IOException e) {
this.showStatus(e.toString());
say("Verbindung zum Server fehlgeschlagen!");
connect = false;
inputfield.disable();
}
}
@SuppressWarnings("deprecation")
public void stop() {
try {
socket.close();
socket = null;
} catch (IOException e) {
//this.(e.toString());
}
if ((thread !=null) && thread.isAlive()) {
thread.stop();
thread = null;
}
}
@SuppressWarnings("deprecation")
public void run() {
String line;
try {
Thread.sleep(100);
while(true) {
line = in.readLine();
if(line != null || !line.equals("")) {
outputarea.appendText(line + "\n");
}
}
} catch (IOException e) {
//say("Verbindung zum Server abgebrochen");
} catch(Exception e) {
say("Verbindung zum Server abgebrochen");
connect = false;
inputfield.disable();
}
}
public boolean action(Event e, Object what) {
if (e.target == inputfield) {
String inp = (String) e.arg;
out.println(inp);
inputfield.setText("");
return true;
}
return false;
}
@SuppressWarnings("deprecation")
public void say(String msg) {
outputarea.appendText("*** "+ msg +" ***\n");
if(ip != null && connect == false) {
outputarea.appendText(ip + " betritt den Raum!\n");
} else if(ip != null && connect == true) {
outputarea.appendText(ip + " verlässt den Raum!");
}
}
public void setLocalPort(int localport) {
this.localport = socket.getLocalPort();
}
public int getLocalPort() {
return localport;
}
}