Newer
Older
nonet / UDPServer.java
@Andreas Jaggi Andreas Jaggi on 4 May 2006 1 KB Initial commit
import java.net.*;
import java.io.*;
import java.nio.*;

public class UDPServer {
	private DatagramSocket sock;
	private CnFrameUDP gui;

	public static void main ( String[] args ) {
		CnFrameUDP gui = new CnFrameUDP("Title of the window");
		UDPServer udpS = new UDPServer(gui);
		udpS.loop();
	}

	UDPServer ( CnFrameUDP gui ) {
		this.gui = gui;
		try {
			sock = new DatagramSocket(13371);
		} catch ( SocketException se ) {
			System.out.println("Couldn't create socket.");
		}
	}

	public void loop ( ) {
		int buffsize = 4096;
		byte[] buff = new byte[buffsize];
		byte[] head = new byte[3];
		byte[] addr = new byte[4];
		byte[] load = new byte[buffsize-7];
		DatagramPacket rp;
		String data;

		while ( true ) {
			rp = new DatagramPacket(buff, buff.length);
			try {
				sock.receive(rp);
			} catch ( IOException ioe ) {
				System.out.println("IO-Error");
			}

			ByteBuffer bb = ByteBuffer.wrap(rp.getData());
			bb.get(head);
			bb.get(addr);
			bb.get(load);

			//System.out.println(rp.getAddress().toString() + ":" + Integer.toString(rp.getPort()) + " > " + new String(load));
			try {
				System.out.println(InetAddress.getByAddress(addr).toString() + " > " + new String(load).trim());
				gui.appendBroadcastMessage(InetAddress.getByAddress(addr).toString(), new String(load).trim());
			} catch ( UnknownHostException uhe ) {
				System.out.println("Errornous packet address");
			}
		}
	}
}