import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;
/**
*
* @author Colin Clausen
*/
public class SimpleChat {
public static void main(String[] args) {
SimpleChat chat = new SimpleChat();
Scanner sc = new Scanner(System.in);
System.out.println("IP-Addresse des Chat-partners:\n");
String ip = sc.next();
try {
chat.connect(InetAddress.getByName(ip));
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("Chat mit "+ip+", zum Beenden \"CloseChat\" eingeben!");
String txt = null;
do {
txt = sc.nextLine();
if (txt.equals("CloseChat")) {
break;
} else {
try {
chat.sendMsg(txt);
} catch (Exception ex) {
ex.printStackTrace();
}
}
} while(true);
chat.disconnect();
}
public static final int PORT = 4711;
private DatagramSocket socket;
private InetAddress partner;
private Thread msgReceiverThread;
private volatile boolean listening;
public void sendMsg(String msg) throws IOException {
byte[] data = msg.getBytes();
socket.send(new DatagramPacket(data, data.length, partner, PORT));
}
private void msgReceived(String msg) {
System.out.println(">"+msg);
}
public void disconnect() {
listening = false;
socket.close();
}
public void connect(InetAddress p) throws SocketException {
if (!listening) {
listening = true;
partner = p;
socket = new DatagramSocket(PORT);
Runnable runner = new Runnable() {
@Override
public void run() {
while (listening) {
try {
byte[] data = new byte[1024];
DatagramPacket msg = new DatagramPacket(data, data.length);
socket.receive(msg);
msgReceived(new String(msg.getData()).trim());
} catch (IOException ex) {
if (!listening) {
break;
} else {
ex.printStackTrace();
}
}
}
}
};
msgReceiverThread = new Thread(runner);
msgReceiverThread.start();
}
}
}