Routing-Packets-In-A-Network-Overlay / src / main / java / csx55 / overlay / transport / TCPSenderThread.java
TCPSenderThread.java
Raw
package csx55.overlay.transport;

import java.io.*;
import java.net.*;

public class TCPSenderThread extends Thread {
    private Socket socket;
    private DataOutputStream dout;

    public TCPSenderThread(Socket socket) throws IOException {
        this.socket = socket;
        dout = new DataOutputStream(socket.getOutputStream());
    }

    /**
     * Used to send data to the nodes/registry's socket. It accepts a byte array and
     * writes that to the data output stream of the socket, which is read by the receiver.
     * @param dataToSend
     * @throws IOException
     */
    public void sendData (byte[] dataToSend) throws IOException {
        try {
            int dataLength = dataToSend.length;
            dout.writeInt(dataLength);
            dout.write(dataToSend, 0, dataLength);
            dout.flush();
        }
        catch (IOException ioe) {
            System.out.println("There was an error when sending the data using TCPSenderThread");
        }
    }

    /**
     * closes the data output stream of this sender
     * @throws IOException
     */
    public void close() throws IOException {
        this.dout.close();
    }

    //returns the socket associated with this sender
    public Socket getSocket() {
        return this.socket;
    }
}