/*
* Created on 2004-02-03
*/
package main;
import window.*;
import java.net.*;
import javax.swing.*;
/**
* @author Robert Rybiański
* @version 0.0
*/
public class Chat {
public static String name;
public static InetAddress host;
public static int clientPort = 55555;
public static int serverPort = 44444;
public static int bufferSize = 99999;
public static DatagramSocket dsIn, dsOut;
public static byte bufferIn[] = new byte[bufferSize];
public static byte bufferOut[] = new byte[bufferSize];
private static SwingWindow sw;
public static boolean stopReceive;
public static void main(String[] args) {
sw = new SwingWindow("Chat v0.0 - 2004 by Robert Rybiański");
try {
name = InetAddress.getLocalHost().toString();
if (args.length == 1) {
host = InetAddress.getByName(args[0]);
} else {
host = InetAddress.getLocalHost();
}
sw.setTextField(host.toString());
dsIn = new DatagramSocket(clientPort);
dsOut = new DatagramSocket(serverPort);
receiveMessage();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Problems with a connection!", "Error", JOptionPane.ERROR_MESSAGE);
System.out.println(e);
}
}
public static void receiveMessage() {
try {
while (true) {
DatagramPacket p = new DatagramPacket(bufferIn, bufferIn.length);
dsIn.receive(p);
while (stopReceive);
sw.setMessage(new String(p.getData(), 0, p.getLength()));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Impossible to receive a message!", "Error", JOptionPane.ERROR_MESSAGE);
System.out.println(e);
}
finally {
receiveMessage();
}
}
public static boolean sendMessage(String str) {
int pos = 0;
while (pos < str.length() && pos < bufferSize) {
bufferOut[pos] = (byte) str.charAt(pos);
pos++;
}
try {
String string = sw.getTextField();
if (string.indexOf("/") >= 0) {
host = InetAddress.getByName(string.substring(0, string.indexOf("/")));
} else {
host = InetAddress.getByName(string);
}
dsOut.send(new DatagramPacket(bufferOut, pos, host, clientPort));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "The incorrect host (domain / IP)!", "Error", JOptionPane.ERROR_MESSAGE);
System.out.println(e);
return false;
}
return true;
}
}