%Set up serial connection
mcu = serial('COM9','BaudRate',9600,'DataBits',8,'StopBits',1);
%set up tcpip connection
input_port = 8080;
output_port = 8080;
import java.net.ServerSocket
import java.net.Socket
import java.io.*
%server_socket = ServerSocket(output_port);

%while(1)
    %Open the serial port
    %fopen(mcu);
    %Send the character 'L' to the mcu
    %fwrite(mcu,'L','char');
    %Close the serial port
    %fclose(mcu);
    %Reopen the serial port, this time for receiving
    %fopen(mcu);
    %print the system time to the Matlab window
    %out = fscanf(mcu)
    %Close the serial port
    %fclose(mcu);
    
    %server_socket = ServerSocket(input_port);
    %input_socket = server_socket.accept; % can timeout
    %output_stream = input_socket.getOutputStream;
    %buffered_output_stream = BufferedOutputStream(output_stream);
    %d_output_stream = DataOutputStream(buffered_output_stream);
    
    
    
    output_socket = Socket('128.253.43.33', output_port);
    output_stream = output_socket.getOutputStream;
    buffered_output_stream = BufferedOutputStream(output_stream); % optional
    d_output_stream = DataOutputStream(buffered_output_stream);
    
    server_socket = ServerSocket(input_port);
    input_socket = server_socket.accept;
    instream = input_socket.getInputStream
    b_instream = BufferedInputStream(instream)
    
    while(1)
        k = 0;
        while(k<21)
            output_stream.write(k)
            k=k+1
        end;
        str=0;
        while(str<20)
            str = instream.read
        end;
        %server_socket.close;
        pause(5)
    end;
    
    %input_socket = Socket('128.84.82.169', input_port);
    %input_stream = input_socket.getInputStream;
    %buffered_input_stream = BufferedInputStream(input_stream); % optional
    %d_input_stream = DataInputStream(buffered_input_stream); 
%end;