/* *Class Sender * *Created by Martin Carlsson * *Internetprogrammering 1 - Course **/ import java.awt.*; import java.net.*; import java.io.*; /**Class Sender is a class for sending information to the opponent peer.*/ public class Sender { private int toPort; // sending port, port to send to private InetAddress toAdr; // Internet address to send to private DatagramSocket socket; // socket to send over private MagnificentBall gui; private GameArea gA; /** *Constructs a Sender object to send data within Datagrampackets to the opponent. *@param toAdr address to send to *@param toPort port to connect to *@param gui reference to the GUI(MagnificentBall) *@param gA reference to the game area(GameArea) *@see java.net.DatagramPacket *@see MagnificentBall *@see GameArea */ public Sender(InetAddress toAdr, int toPort, MagnificentBall gui, GameArea gA) { this.toAdr = toAdr; this.toPort = toPort; this.gui = gui; this.gA = gA; try { socket = new DatagramSocket(); gA.setConnected(true); } catch(SocketException se) { gA.disconnect(); } } /** *Sends datagram packets to the opponent peer *@param x player 1's reversed x-position (used in case of future developement where the player can move horizontally) *@param y player 1's, i.e. one's owns y-position *@param l player 2's life *@param c player 2 score *@param l2 player 1's life *@param c2 player 1's score *@param toSend describes what is being sent */ protected synchronized void sendAway(int x, int y, int l, int c,int l2, int c2,String toSend) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); if(toSend.equals("activ")) dos.writeChar('a'); else if(toSend.equals("inActiv")) dos.writeChar('i'); else if(toSend.equals("stoped")) dos.writeChar('s'); else if(toSend.equals("resumed")) dos.writeChar('r'); else if(toSend.equals("hit")) dos.writeChar('h'); else if(toSend.equals("ball")) { dos.writeChar('b'); dos.writeInt(x); dos.writeChar('\t'); dos.writeInt(y); } //slut else if else if(toSend.equals("player")) { dos.writeChar('p'); dos.writeInt(x); dos.writeChar('\t'); dos.writeInt(y); } else if(toSend.equals("newGame")) dos.writeChar('n'); else if(toSend.equals("gameOver")) dos.writeChar('g'); else if(toSend.equals("quit")) dos.writeChar('q'); else if(toSend.equals("lifeAndScore")){ dos.writeChar('l'); dos.writeInt(l); dos.writeChar('\t'); dos.writeInt(c); dos.writeChar('\t'); dos.writeInt(l2); dos.writeChar('\t'); dos.writeInt(c2); } dos.flush(); dos.close(); // closes DataOutputStream byte[]data = baos.toByteArray(); DatagramPacket packet = new DatagramPacket(data, data.length, toAdr, toPort); // creates a DatagramPacket to toAdr against port toPort socket.send(packet); // sends the packet } catch(IOException ioe) { } } // end sendAway() /** *Closes socket for outgoing traffic */ public void closeSendSocket() { try { socket.close(); } catch(Exception e) { } } }//End class Sender