/*
 * Created on Sep 14, 2004
 *
 */

/**
 * @author tamer
 *
 */
package communication;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Communicator {
private int port;
private InetAddress host;
private DatagramSocket socket;

	public Communicator(){
		try{
			host = InetAddress.getByName("localhost");
			port = 6000;
			socket = new DatagramSocket();	
		}catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void send(String message){
		try{
			message = message + "\u0000"; //\u0000, weil Nachrichten Nullterminiert sein muessen 
			byte send_data[] = message.getBytes(); //Umwandeln in bytes
			DatagramPacket send_packet = new DatagramPacket( send_data, send_data.length, host, port); //UDP Paket erstellen
			socket.send(send_packet); //Paket absenden
		} catch (IOException e) {
			e.printStackTrace();
		} 			
	}	
	
	public String receive(){
		String message = null;
		try{
			DatagramPacket receive_packet = new DatagramPacket(new byte[4096], 4096);
			socket.receive(receive_packet);
			byte receive_data[] = receive_packet.getData();
			message = new String(receive_data).trim(); 
			port = receive_packet.getPort(); //evtl. port auslagern
		}catch (IOException e) {
			e.printStackTrace();
		} 
		return message;
	}
}
