package udpchatserver; /** * Title: UDPChatServer * Description: UDPChatServer * Copyright: Copyright (c) 2001 * Company: * @author: Dan * @version 1.0 */ import java.net.* ; import java.io.* ; import java.lang.* ; import java.util.* ; public class ChatServer{ //set the global variables which are passed/referenced by sub classes static final int BUFFER_SIZE = 512; //Sets Max Packet Size private DatagramSocket ChatSocket = null; //Socket to Communicate with public Hashtable ClientsTable = new Hashtable(); public ChatServer(int Port) { int ServerPort = Port; //Create buffers to hold incoming & outgoing messages byte[] recievedBuffer = new byte[BUFFER_SIZE]; byte[] sendBuffer = new byte[BUFFER_SIZE]; while(true){ try { //Sets up DatagramSocket on the Server Port ChatSocket = new DatagramSocket(ServerPort); System.out.println("Chat Server started on " + InetAddress.getLocalHost()); do { //Block until a Datagram appears byte [] buf = new byte [BUFFER_SIZE]; DatagramPacket IncomingPacket = new DatagramPacket(buf, buf.length); ChatSocket.receive(IncomingPacket); ChatServerThread ChatThread = new ChatServerThread(IncomingPacket, GetHashTable()); ChatThread.start(); }while(true); }catch (SocketException e) { System.err.println("Can't open OutToClientSocket"); System.exit (1); }catch (IOException e) { System.err.println("Communication error"); e.printStackTrace (); }finally { ChatSocket.close(); } } } public Hashtable GetHashTable(){ return ClientsTable; } public static void main (String args []) throws Exception { ChatServer p; int localport = -1; int i = 0; boolean error = false; Integer parselocalport = new Integer(args[i]); try{ localport = parselocalport.parseInt(args[i], 10); } catch(Exception e){ System.err.println("Error: " + e.getMessage() + "\n"); error = true; } if(localport <= 0){ System.err.println("Error: Invalid Local Port Specification " + "\n"); error = true; } try{ if (args.length!=1) throw new IllegalArgumentException("Syntax: chatserver "); } catch (Exception ex){ System.err.println(ex.getMessage()); System.exit(1); } if(error) System.exit(-1); try{ p = new ChatServer(Integer.parseInt(args[0])); p.ChatSocket.disconnect(); } catch(Exception ex){ System.err.println("Error: " + ex.getMessage()); System.exit(1); } finally{ System.out.println("Closing..."); } } }