TIdHTTP GET Round Trip Request/Response Time in MSecs - c++builder

I'm using TIdHTTP to make HTTP GET requests to get wiki pages (executed until x >= 9 times using a for loop statement).
I am trying to use TStopWatch to measure the HTTP round trip request/response time in milliseconds of each GET requests.
I have tried somes methods, but, I still in doubt that it was right or not. So, please tell me what's the right method to do that. Thank you.
Btw, the code I have is:
//---------------------------------------------------------------------------
int MSec = 0;
TTimeSpan TTSpan;
TDateTime StartTime;
DWORD AStartTime = 0;
DWORD CStartTime = 0;
String ACount, Codes, Milli, Result;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner)
{
IdHTTP->ConnectTimeout = 3048;
IdHTTP->ReadTimeout = 2048;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::IdHTTPWork(TObject *ASender, TWorkMode AWorkMode, __int64 AWorkCount)
{
if (AWorkMode == wmRead)
ACount = "size: [" + String(AWorkCount) + " bytes]";
}
//---------------------------------------------------------------------------
void __fastcall TForm1::WorkClick(TObject *Sender)
{
static int Number = 1;
TStopwatch SWatch = TStopwatch::StartNew();
// CStartTime = GetTickCount();
// DWORD Start = timeGetTime();
// AStartTime = GetTickCount();
// CStartTime = TTSpan.Milliseconds;
Work->Enabled = false;
ListBox->Items->Clear();
ListBox->Items->BeginUpdate();
for (int i = 0; i < 9; i++)
{
try
{
SWatch.Start();
try
{
IdHTTP->Get("http://en.wikipedia.org/");
Sleep(1000);
}
catch (const Exception &E)
{
Label1->Caption = E.Message;
}
SWatch.Stop();
TTSpan = SWatch.Elapsed;
MSec = TTSpan.Milliseconds;
// MSec = TTSpan.Milliseconds / 10;
// MSec = SWatch.ElapsedMilliseconds / 10;
// TTSpan = SWatch.Elapsed;
// MSec = TTSpan.Milliseconds - CStartTime;
Milli = " time: [" + String(MSec) + " ms]";
Codes = " code: [" + IdHTTP->Response->ResponseText.LowerCase() + "]";
ListBox->Items->Add("(" + String(Number++) + "). " + ACount + Codes + Milli);
// AStartTime = GetTickCount();
// ListBox->Items->Add("(" + String(Number++) + "). " + ACount + Codes + Result.sprintf(L" time: [%i ms]",(aStartTime-bStartTime)));
}
__finally
{
Work->Enabled = true;
IdHTTP->Disconnect(true);
ListBox->Items->EndUpdate();
}
}
}

Related

Can not read data sent form mobile..Shows Unrecognized text in WireShark

I am capturing data sent form a mobile device to my local server. I am not getting expected data in my computer so I tried WireShark to capture the data to see whats going on. The data is successfully received by WireShark but it shows Unrecognized text.
(source: pbrd.co)
I have tired the following code to receive the data programmatically:
public class Server {
public static void main(String[] args) {
int port = 9090;
try (ServerSocket serverSocket = new ServerSocket(9090)) {
System.out.println("Server is listening on port " + port);
while (true) {
Socket socket = serverSocket.accept();
System.out.println("New client connected");
InputStream inputStreamm = socket.getInputStream();
FileOutputStream mFileOuptutStream = new FileOutputStream("output.txt");
byte[] fileBytes = new byte[100];
int fByte = inputStreamm.read(fileBytes);
int i = 0;
while (fByte > 0) {
mFileOuptutStream.write(fileBytes, 0, fByte);
fByte = inputStreamm.read(fileBytes);
i++;
}
mFileOuptutStream.close();
System.out.println("New file created");
inputStreamm.close();
socket.close();
}
} catch (IOException ex) {
System.out.println("Server exception: " + ex.getMessage());
ex.printStackTrace();
}
}
}
I have used following code example to send the data to the server.
myhttp.sendtohttp(getrecorddate(upload_id),String.format(Locale.ENGLISH, url, ip, port));
public byte[] getrecorddate(int ID) {
Log.i("getrecorddate", "11111");
GlobalRecord uploadRecord = upload_db.readDbFile(sqlite_cmd.RecordTable, ID);
String jpg_filename = String.format(Locale.ENGLISH, "well%05d.jpg", ID);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int dataLen = 0;
int recordLen = 0;
byte strFormData[] = new byte[100];
for (int i = 0; i < 100; i++)
strFormData[i] = 0;
strFormData[0] = 0x68;
strFormData[1] = (byte) 0x99;
strFormData[2] = (byte) 0x88;
strFormData[3] = (byte) 0x77;
strFormData[4] = 0x78;
strFormData[5] = 0x01;
strFormData[6] = 0x09;
strFormData[7] = 0x68;
strFormData[8] = (byte) 0x84;
strFormData[11] = 0x50;
strFormData[12] = 0x00;
strFormData[21] = 0x01;
baos.write(strFormData, 0, 28);
byte[] jpgBuf = null;
int jpgLen = 0;
try {
String fileName = GlobalFinalValues.RECORD_PATH + "Num00/SubNum000/" + jpg_filename;
fileName = uploadRecord.String_Record[34];
FileInputStream fin = new FileInputStream(fileName);
jpgLen = fin.available();
jpgBuf = new byte[jpgLen];
fin.read(jpgBuf);
fin.close();
baos.write(jpgBuf, 0, jpgLen);
} catch (Exception e) {
jpgLen = 0;
e.printStackTrace();
}
if (uploadRecord != null) {
try {
// String jpg_filename="well00001.jpg";
byte[] jpg_name = jpg_filename.getBytes("UTF-8");
int jpg_filelen = jpg_name.length;
baos.write(jpg_filelen);
baos.write(jpg_name, 0, jpg_filelen);
baos.write(0xff);
recordLen = jpg_filelen + 2;
for (int i = 1; i < 15; i++) {
int m;
if (i > 7) m = i + 6;
else m = i;
if (i == 14) m = 35;
String str = uploadRecord.String_Record[m];
if (m == 35) {
str = uploadRecord.String_Record[35] + ";" + uploadRecord.String_Record[36];
}//GPS
if (str.length() > 50) str = str.substring(0, 50);
byte[] srtbyte = str.getBytes("UTF-8");
int len = srtbyte.length;
baos.write(len % 256);
if (len > 0)
baos.write(srtbyte, 0, len);
baos.write(0xff);
recordLen += len + 2;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
baos.write(recordLen / 256);
baos.write(recordLen % 256);
baos.write(0xff);
recordLen += 3;
baos.write(0);
baos.write(0x16);
byte[] data = baos.toByteArray();
dataLen = data.length;
data[9] = (byte) ((dataLen - 13) % 65536 / 256);
data[10] = (byte) ((dataLen - 13) % 65536 % 256);
data[13] = (byte) ((dataLen - 13) / 65536);
//data[14] = (byte) ((dataLen - 13) / 65536 % 256);
data[dataLen - 2] = 0x00;
for (int i = 0; i < (dataLen - 2); i++)
data[dataLen - 2] += data[i];
return data;
}
public boolean sendtohttp(byte strFormData[], String url) {
boolean back = false;
HttpURLConnection urlConnection = null;
try {
int dataLen = strFormData.length;
urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setFixedLengthStreamingMode(dataLen);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type",
("application/xml; charset=utf-8").replaceAll("\\s", ""));
OutputStream out = urlConnection.getOutputStream();
out.write(strFormData, 0, dataLen);
out.close();
int responseCode = urlConnection.getResponseCode();
InputStream in = null;
if (responseCode == 200) {
in = new BufferedInputStream(urlConnection.getInputStream());
} else {
in = new BufferedInputStream(urlConnection.getErrorStream());
}
byte readbuf[] = new byte[100];
int readlen = in.read(readbuf, 0, 100);
String str = new String(readbuf, 0, readlen, "UTF-8");
if (str.equals("succ")) {
back = true;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return back;
}
I am new to this technique would really appreciate if you can guide me.
I am expecting the data to be in text but I am getting following output:
POST /alky_gps_server/alky/send9_1 HTTP/1.1
Content-Type: application/xml;charset=utf-8
Content-Length: 25925
User-Agent: Dalvik/2.1.0 (Linux; U; Android 5.1.1; AOSP on Drone Build/LMY48G)
Host: 192.168.0.75:9090
Connection: Keep-Alive
Accept-Encoding: gzip
h��wx h�e8P ���� JFIF �� C

%# , #&')*)-0-(0%()(�� C

(((((((((((((((((((((((((((((((((((((((((((((((((((�� ��" ��
�� � } !1AQa"q2���#B��R��$3br�
%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz���������������������������������������������������������������������������
�� � w !1AQaq"2�B���� #3R�br�
$4�%�&'()56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������  ? �#�~T׵9m��g&�����#��) n�9�h<�V�l5�y4�i���)1�zhM��� v�(��B���ݹ��܎�:��<� �B�G8�����Ҍm� ��1DIhj�g=iTg�"�~�&� � �b�(�Fj�A�;��
"�����P-�Ҝ�����c�Gʝ�=(sFp=���;�#��P1��N�84�3
�qN^�����_ژ���S�z�㎴�qސ�z������I��ļ� ���4���p�ۧ�#=9(^��dNP:H"7#<P�<�t����LOAXp �t�<����=:PTE���9xjS�8}i���s�4|٧�<�N��-E�{pi��<�G^��N�v�
!c4(��:��g֌�ȡ{�^i ϩ�J u�{�/Niz�P5�hLsN�q�A �s#�=r��=�����2�1B�)�ڐ��x ���BM9�)�gЉ���i#�JR8��i99�9�SH���(�8�k�^GJiG=iFH�h��M ���v� s�R q�v�.��ܯ'�GN��+c={Q���!��#ph^ �zU��H�,)��F�J^~��F����$��0s�jM��
�M;�g<�r�"�&����H���hM���N^=��Hu��n��4���o$Ҩ �#�]g����F�-bM8�V�,KjKmE#&F��
��H���z~�>�����uxe����Vh���O�3�1D4f5������6����i���U3yr�E���:���>��z���k7��?:[5�4�\��~5�j�����������Z�RFm��$��Y�}����l5��N�ÚY���.��D`y'v2A�=kE�0��+G���{a�+��=Sϱ��}�Iq8NT�o=�8��4{�������s�[�?%�4�q��<)���?��6O�\� �B�������6���g��W�z�

JtextField Variable Grab and Use for Numerical Iteration from GUI

this is my complete code for a small gui to take variables from user and return them to the rest of program(r.o.p) for calculations, however doesn't seem to be passing to r.o.p. and no output file is observerd.
Any help would be much appreciated, I think the problem is with the listener for the Draw New Graph command. Thanks
Code:
import java.text.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class RungeKutta {
// class to create slider and window
private static File file1;
public static double A(double v, double x, double wc, double beta) {
return (-2 * beta * v - (Math.pow(wc, 2)) * Math.sin(x));
}
public static File getFile1() {
return file1;
}
public static void setFile1(File file1) {
RungeKutta.file1 = file1;
}
public static void main(String[] argv) throws IOException, ParseException {
createAndShowGUI();
}
private static void createAndShowGUI() {
//create and set up the window.
JFrame frame = new JFrame("RungeKutta");
GridLayout first = new GridLayout(14,1);
frame.setLayout(first);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create, name and Populate TextField
JTextField PL = new JTextField("Pendulum Length", 20);
//Set TextField to Uneditable. Each will have Empty Field Below For Variables
PL.setEditable(false);
//Set Textfield for user entered dat
JTextField PLv = new JTextField();
//Allow input from text field to be taken
JTextField AD = new JTextField("Angular Displacement", 20);
AD.setEditable(false);
JTextField ADv = new JTextField();
JTextField AV = new JTextField("Angular Velocity", 20);
AV.setEditable(false);
JTextField Avv = new JTextField();
JTextField TS= new JTextField("Time Steps", 20);
TS.setEditable(false);
JTextField TSv = new JTextField();
JTextField MT = new JTextField("Max Time", 20);
MT.setEditable(false);
JTextField MTv = new JTextField();
JTextField V = new JTextField("Viscosity (0-1)", 20);
V.setEditable(false);
JTextField Vv = new JTextField();
//Create Button to Restart and Button to take in Values for usage
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(600,500));
frame.getContentPane().add(PL, first);
frame.getContentPane().add(PLv, first);
frame.getContentPane().add(AD, first);
frame.getContentPane().add(ADv, first);
frame.getContentPane().add(AV, first);
frame.getContentPane().add(Avv, first);
frame.getContentPane().add(TS, first);
frame.getContentPane().add(TSv, first);
frame.getContentPane().add(MT, first);
frame.getContentPane().add(MTv, first);
frame.getContentPane().add(V, first);
frame.getContentPane().add(Vv, first);
JButton BNewGraph = new JButton("Draw New Graph"); //Button to restart entire drawing process
frame.getContentPane().add(BNewGraph, first);
//display the window
frame.pack();
frame.setVisible(true);
class intakegui implements ActionListener
{
public intakegui()
{
BNewGraph.addActionListener((ActionListener) this);
BNewGraph.setActionCommand("Click to Draw");
}
#Override
public void actionPerformed(ActionEvent e) {
double l = Double.parseDouble(PLv.getText());
double xi = Double.parseDouble(ADv.getText());
double vi = Double.parseDouble(Avv.getText());
double dt = Double.parseDouble(TSv.getText());
double n = Double.parseDouble(MTv.getText());
double beta = Double.parseDouble(Vv.getText());
SimpleDateFormat dform = new SimpleDateFormat("ddMMyyyysmH");
Date d = Calendar.getInstance().getTime();
String dstr = dform.format(d);
String filename = ("result " + dstr + ".txt");
file1 = new File(filename);
PrintWriter savedValues = null;
try {
savedValues = new PrintWriter(filename);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//declare variable for gravity and omega*c
double g = 9.8;
double wc = Math.sqrt(g / l);
savedValues.println("#Initial Values Entered");
savedValues.println("#" + l + "," + vi + "," + xi + "," + dt + "," + n
+ "," + beta);
double[] dispTime = new double[(int) n];
double[] velTime = new double[(int) n];
// let a = angular acceleration
for (double j = 0; j < (int) n; j++) {
// int time = 1;
double k1v = dt * j * A(vi, xi, wc, beta);
double k1x = dt * j * vi;
double k2v = dt * j * A(vi, xi + (0.5 * k1x), wc, beta);
double k2x = dt * j * (vi + (0.5 * k1v));
double k3v = dt * j * A(vi, xi + (0.5 * k2x), wc, beta);
double k3x = dt * j * (vi + (0.5 * k2v));
double k4v = dt * j * A(vi, xi + k3x, wc, beta);
double k4x = dt * j * (vi + k3v);
xi += k1x / 6 + k2x / 3 + k3x / 3 + k4x / 6;
vi += k1v / 6 + k2v / 3 + k3v / 3 + k4v / 6;
dispTime[(int) j] = xi;
velTime[(int) j] = vi;
System.out.println(xi + "," + vi);
}
for (int i = 0; i < (int) n; i++) {
savedValues.println(dispTime[i] + " " + velTime[i]);
}
savedValues.close();
System.out.println("File saved. File name: " + filename);
}
}
}
}
You forgot to add listener to your button. You need to add listener as below:
BNewGraph.addActionListener(new intakegui());
Now when user clicks on button, you would see the file.

Navigate through Array by Pointer to Pointer

I have tried to move through array by double pointer. Here is the Code.
void pptr (int **sptr2,int **ptr2)
{
**ptr2 = (**sptr2 + 7); //Works Fine
*sptr2++; *ptr2++; //Probable problem Statement
**ptr2 = (**sptr2 + 7); //Not Workign
}
void ppointer (int *sptr,int *ptr)
{
pptr (&sptr,&ptr);
}
main()
{
int sour[2];
sour[0] = 40;
sour[1] = 50;
int var[2];
var[0] = 10;
var[1] = 20;
printf("befor change %d %d\n",var[0],var[1]);
ppointer(&sour[0],&var[0]);
printf("pointer to pointer change %d %d\n",var[0],var[1]);
}
I wish to update var in pptr function. I can use double pointer (**sptr,**pptr) to reference pointer (sptr,ptr) (which are pointing to array) into function. I am able to update first one but second one has no change. I think problem is with statement *sptr++ & *ptr++.
Please help me understand how can i navigate through array by double pointer.
Thank you
I think it is the compiler just being silly with the "*sptr++;" and the "*ptr++;"
void pptr (int **sptr2, int **ptr2)
{
**ptr2 = (**sptr2 + 7);
///////////////////////////////////////////////////////
*sptr2++; //This is the problem these two statements
*ptr2++;
///////////////////////////////////////////////////////
**ptr2 = (**sptr2 + 7);
}
Now however if you change it to "*sptr2 += 1;" and "*ptr += 1;" it then works
void pptr (int **sptr2, int **ptr2)
{
**ptr2 = (**sptr2 + 7);
///////////////////////////////////////////////////////
*sptr2 += 1; //Now no problem
*ptr2 += 1;
///////////////////////////////////////////////////////
**ptr2 = (**sptr2 + 7);
}
I dont really know why the compiler does this due to lack of experience of using the "variable++" operator, I just generally use "variable += 1" instead.

Currency formatting for BlackBerry when locale set to French

I've writing an app that requires French language support. I'm having trouble getting currency to format correctly when the locale is set to FR. Is there any way to do this correctly?
I had to do it myself.
Created a "Formatter" class extending AFormatter with the following methods
Don't now how it is in France but in Argentina we use the following format 10.000.000,18 for example.
Hope it's helps or that someone provides a better solution
public static String addCommas(String s) {
int extraRound = 0;
boolean negative = false;
int c;
if(s.charAt(0) == '-') {
negative = true;
s = s.substring(1);
}
int len = s.indexOf('.')==-1?s.length():s.indexOf('.');
if(len > extraRound + 3) {
c = len - extraRound - 3;
s = s.substring(0, c) + "," + s.substring(c);
}
if(len > extraRound + 6) {
c = len - extraRound - 6;
s = s.substring(0, c) + "," + s.substring(c);
}
if(len > extraRound + 9) {
c = len - extraRound - 9;
s = s.substring(0, c) + "," + s.substring(c);
}
if(len > extraRound + 12) {
c = len - extraRound - 12;
s = s.substring(0, c) + "," + s.substring(c);
}
if(negative) {
s = '-' + s;
}
return s;
}
public static String addCommasNew(String s) {
int extraRound = 0;
boolean negative = false;
int c;
if(s.charAt(0) == '-') {
negative = true;
s = s.substring(1);
}
int len = s.indexOf(',')==-1?s.length():s.indexOf(',');
if(len > extraRound + 3) {
c = len - extraRound - 3;
s = s.substring(0, c) + "." + s.substring(c);
}
if(len > extraRound + 6) {
c = len - extraRound - 6;
s = s.substring(0, c) + "." + s.substring(c);
}
if(len > extraRound + 9) {
c = len - extraRound - 9;
s = s.substring(0, c) + "." + s.substring(c);
}
if(len > extraRound + 12) {
c = len - extraRound - 12;
s = s.substring(0, c) + "." + s.substring(c);
}
if(negative) {
s = '-' + s;
}
return s;
}
public static String removeScientific(String s) {
int eIndex = s.indexOf('E');
int initialPos = s.indexOf('.');
String result = s;
if (eIndex != -1){
int base = Integer.parseInt(s.substring(eIndex+1));
String pre = s.substring(0, initialPos);
String pos = s.substring(initialPos+1, eIndex);
String pos1 = "";
if (base < pos.length()){
String pos1a = pos.substring(0, base);
String pos1b = pos.substring(base, pos.length());
pos1 = pos1a + "." + pos1b;
} else {
pos1 = pos.substring(0, pos.length());
for (int i = 0; i < base-pos.length(); i++){
pos1 = pos1 + "0";
}
}
result = pre + pos1;
}
return result;
}
public static String changePointToComma(String s){
int initialPos = s.indexOf('.');
String result = s;
if (initialPos != -1){
result = s.substring(0, initialPos) + "," + s.substring(initialPos + 1, s.length());
}
return result;
}
public static String changeCommaToPoint(String s){
int initialPos = s.indexOf(',');
String result = s;
if (initialPos != -1){
result = s.substring(0, initialPos) + "." + s.substring(initialPos + 1, s.length());
}
return result;
}
public static String removeNumberFormat(String s){
int initialPos = s.indexOf('.');
String result = s;
if (initialPos != -1){
result = s.substring(0, initialPos) + s.substring(initialPos + 1, s.length());
result = Formatter.removeNumberFormat(result);
} else {
return result = Formatter.changeCommaToPoint(s);
}
return result;
}
public static String roundDouble(String s, int presicion){
int initialPos = s.indexOf('.');
String result = s;
String pre;
String pos;
if (initialPos != -1){
pre = s.substring(0, initialPos);
pos = s.substring(initialPos + 1, s.length());
if (presicion < pos.length()){
pos = s.substring(initialPos + 1, initialPos + 1 + presicion );
int dec = Integer.parseInt(pos);
int next = Integer.parseInt(s.substring(initialPos + 1 + presicion, initialPos + 2 + presicion )); //to round the las digit
if (next > 4){
dec = dec + 1;
pos = dec + "";
if ((dec+"").length() > presicion){
pre = (Integer.parseInt(pre) + 1) + "";
pos = "0";
}
}
} else {
}
result = pre + "." + pos;
}
return result;
}

Lejos RGB color sensor

Does anyone have a code example of using the NXT RGB Color Sensor in the Lejos programming language. I have tried several different uses of setType() and setMode() but to no avail.
Here is some working code:
ColorLightSensor cs = new ColorLightSensor(SensorPort.S1, SensorConstants.TYPE_LIGHT_ACTIVE);
for(int i = 0; i < 100 && !done; i++)
{
cs.setFloodlight(lejos.robotics.Colors.Color.RED);
sleep(1);
LCD.clearDisplay();
LCD.drawString("" + cs.getRedComponent(), 0,0);
cs.setFloodlight(lejos.robotics.Colors.Color.GREEN);
sleep(1);
LCD.clearDisplay();
LCD.drawString("" + cs.getGreenComponent(), 0,0);
cs.setFloodlight(lejos.robotics.Colors.Color.BLUE);
sleep(1);
LCD.clearDisplay();
LCD.drawString("" + cs.getBlueComponent(), 0,0);
}
Here is a simple example for monitoring the NXT 2 color sensor:
import lejos.nxt.*;
import lejos.robotics.*;
public class MyColorSensor {
public static void main(String argv[]) {
ColorSensor cs = new ColorSensor(SensorPort.S1);
for(int i = 0; i < 10; i++) {
Color color = cs.getColor();
System.out.println("Color = " + cs.getColorID() + " " + color.getColor() +
"(" + color.getRed() + "," + color.getGreen() + "," + color.getBlue()
+") " + color.getColor());
Button.waitForAnyPress();
}
}
}

Resources