/* * Author: Wenbing Zhao * Last Modified: 9/18/2006 * For EEC484/584 Project 1 */ import java.io.*; import java.net.*; import java.util.*; public class PhysicalLayer { private InetAddress m_IPAddress; private DatagramSocket m_socket = null; private int m_localport = 0; private int m_remoteport = 0; private byte[] m_receiveBuffer = new byte[Frame.MAX_FRAME_SIZE]; private DataLinkLayer m_datalinkLayer = null; public PhysicalLayer(int localport, int remoteport) { m_localport = localport; m_remoteport = remoteport; try { m_IPAddress = InetAddress.getByName("localhost"); m_socket = new DatagramSocket(localport); } catch(Exception e) { System.out.println("Cannot create UDP socket: "+e); } // start the reading thread new ReadThread().start(); } public void setDataLinkLayer(DataLinkLayer dl) { m_datalinkLayer = dl; } public void send(byte[] payload) { // To be modified // simulate random loss of frame Random rand = new Random(); int randnum = rand.nextInt(10); // range 0-10 if(randnum < 3) return; // simulate a loss try { DatagramPacket p = new DatagramPacket(payload, payload.length, m_IPAddress, m_remoteport); //System.out.println("PhysicalLayer::send: " // +new String(p.getData())); m_socket.send(p); } catch(Exception e) { System.out.println("Error sending frame: "+e); } } // Interface provided to the data link layer to pick // up message received public byte[] receive() { return m_receiveBuffer; } // Thread to read frames arrived from the network and to notify // the data link layer public class ReadThread extends Thread { public void run() { while(true) { DatagramPacket p = new DatagramPacket(m_receiveBuffer, m_receiveBuffer.length); try { m_socket.receive(p); } catch(Exception e) { System.out.println("Cannot receive from socket: "+e); } byte[] receivedData = p.getData(); //System.out.println("Received frame: "+ receivedData[0]); if(m_datalinkLayer != null) m_datalinkLayer.onFrameArrival(); } } } }