I'm requesting data by sending a request command over UDP, and if it works, I'm supposed to receive a response. However, in the case that a response doesn't come through, I want to wait 3 seconds, then send a request again. I want to try this 3 times before "giving up" and displaying an error.
The code I have implemented is currently sending out the request once, but isn't sending it again one it realizes there is no response and I'm not sure where I'm going wrong.
int counter = 0;
static final int Limit = 3;
public void sendReq() {
new Thread((Runnable) () -> {
try {
...
// Sending Request command here ...
// Receiving
while(true) {
DatagramPacket dp = new DatagramPacket(buf, buf.length);
socket.receive(dp);
byte[] response = dp.getData();
if(response.length == 0 || dp == null) {
counter = counter + 1;
if(counter == Limit) {
// give up, display error
} else {
Thread.sleep(3000); // Wait 3 seconds
sendReq();
}
} else {
// Do stuff with response
}
}
}
On the device I'm sending my command to, I made it so it holds its response on the first request, and I know the response isn't coming back. However my code isn't retrying.
What should I do?
Related
I have my below code which can captures packets from the interface using pcap4j but I am not sure how can I print the request and the response data present in the packet. For example, if I make a REST call from a postman then I want to trace the request and response. This is the same as Wireshark. I am stuck in the last part where I am able to capture the packet but not sure how do I read the packet contents which I can print on console.
try {
InetAddress addr = InetAddress.getByName("10.227.178.25");
PcapNetworkInterface device = Pcaps.getDevByAddress(addr);
System.out.println("You chose: " + device);
int snapshotLength = 64 * 1024; // in bytes
int readTimeout = 50; // in milliseconds
final PcapHandle handle;
handle = device.openLive(snapshotLength, PromiscuousMode.PROMISCUOUS, readTimeout);
String filter = "tcp port 80";
handle.setFilter(filter, BpfCompileMode.OPTIMIZE);
// Create a listener that defines what to do with the received packets
PacketListener listener = new PacketListener() {
#Override
public void gotPacket(Packet packet) {
// Override the default gotPacket() function and process packet
System.out.println(handle.getTimestamp());
System.out.println(packet);
byte[] b = packet.getRawData();
Packet p = packet.getPayload();
}
};
// Tell the handle to loop using the listener we created
try {
int maxPackets = 50;
handle.loop(maxPackets, listener);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Cleanup when complete
handle.close();
}catch(Exception e) {
e.printStackTrace();
}
So I have two questions :
How can I capture the HTTP request and response and print it on the console.
How can I let the java code run continuously such that it keeps on capturing the packets.
I did check the pcap4j documents but not sure how I can read the packet contents where I can read the HTTP request and HTTP response.
For the first question:
If you set [maxPackets] to -1, it will run continuously.
You can see many such implementations from the official Sample.
As for the second question:
Currently, the official library does not support Http Packet. You need to implement it manually by yourself.
You can check https://github.com/kaitoy/pcap4j/issues/85.
I'm trying to create a simple AMQP application in Java. The application should simply bounce a number between two clients. Each time the number is received the client should add 1 to it and send it back to the other client. However, I cannot get the example to work at all. I can send the first number, but it is never received. In the webinterface of the broker I see zero connections and messages. I am doing something wrong, but can't figure out what it is. Hopefully someone here can spot the error(s). Below is the code I've written.
Messenger mng = Proton.messenger();
mng.start();
mng.subscribe("localhost:5672");
Message msg = Proton.message();
msg.setAddress("localhost:5672");
msg.setSubject("foobar");
if (args.length > 2 && args[2].equals("foo"))
{
System.out.println("Sending initial: 1");
msg.setBody(new AmqpValue("1"));
mng.put(msg);
mng.send();
System.out.println("Sent initial: 1");
}
try
{
while (true)
{
mng.recv(1);
while(mng.incoming() > 0) {
Message message = mng.get();
int consumed = Integer.parseInt(message.getBody().toString());
System.out.println("Received: " + consumed);
consumed = consumed % 100;
if (consumed == 0)
{
long seconds = (System.currentTimeMillis() - start) / 1000;
start = System.currentTimeMillis();
System.out.println("Last hundred messages took (s): " + seconds);
}
msg.setBody(new AmqpValue(""+(consumed+1)));
mng.put(msg);
mng.send();
}
}
}
catch (Exception e)
{
System.out.println("proton error: " + e.getMessage());
}
Well, I turned off my firewall completely and changed the code a bit to listen and subscribe to my local IP address and that worked well for me:
Messenger mng = Proton.messenger();
mng.start();
mng.subscribe("amqp://~xxx.xxx.xxx.xxx");
Message msg = Proton.message();
msg.setAddress("amqp://yyy.yyy.yyy.yyy");
....
I'm kinda new to Java language, but have a good experience in other technologies.
Right now Im working on creating a proxy server and I have come up with the code that seems to work fine for single requests, but when I'm trying to open some html page that loads lots of styles, images etc, part of requests just got aborted ( this is what firebug tells me )
So, will try to simplify the code and be as much specific as possible in showing up the exact problem
Here's the main class :
public class ProxyThread {
public static void main(String[] args) {
ProxyThread Proxy = new ProxyThread();
Proxy.start();
}
public void start() {
ServerSocket server = new ServerSocket(this.portNumber, 1);
while(true) {
Socket serverClient = server.accept();
this._threads[threadCount] = new Thread( new RequestProcess( serverClient, threadCount++ ));
}
}
}
Here's the code of RequestProcess that does processing of each request
public class RequestProcess implements Runnable {
public void start() throws InterruptedException {
this.serverIn = new BufferedReader( new InputStreamReader( this.serverClient.getInputStream() ) );
this.serverOut = this.serverClient.getOutputStream() ;
String currentBuffer;
String request = "";
String host = "";
int port = 0;
while ((currentBuffer = this.serverIn.readLine()) != null) {
if (currentBuffer.length() == 0) {
break;
}
request += currentBuffer + "\r\n";
if (currentBuffer.startsWith("CONNECT ") || currentBuffer.startsWith("GET ")) {
host = this.parseHost( currentBuffer );
port = this.parsePort( currentBuffer );
}
}
request += "\r\n";
if (host.isEmpty() || request.isEmpty()) {
throw new InterruptedException("request or host empty, so exiting ");
}
clientRequestProcess clientProcess = new clientRequestProcess( host, port, request, this.threadNum );
byte[] response = clientProcess.processRequest();
this.serverOut.write(response);
this.serverOut.close();
}
}
And here's the class that process request and sending it to the actual server
public class clientRequestProcess {
public byte[] processRequest()
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte buf[] = new byte[256*1024];
Socket clientSocket = new Socket( host, port );
clientSocket.getOutputStream().write( request.getBytes() );
InputStream is = clientSocket.getInputStream();
int r = 1;
while (r > 0) {
r = is.read(buf);
if (r > 0) {
bos.write(buf, 0, r);
}
}
return bos.toByteArray();
}
}
All the code is draft one and is simplified to show the big picture of how it works. All try-catch blocks, debugging info etc are missed here.
steps
- Set up browser to use JAVA proxy
- Open some site
- Part of http requests are successfully processed and correct response is returned
-part of requests shows up as aborted in firebug. The thing is that part is absolutely random, so one time some file is loading, another it is not
Code troubleshooting shows me that first line of request (that comes from the browser) are empty, so my condition
if (currentBuffer.length() == 0) {
break;
}
breaks reading the socket and thus it ruturns nothing to the browser and connection gets aborted
I read rfc on http protocol and figured out that https requests considered to be over once \r\n meets, so that's why I'm using that condition
If I just open that file in separate tab - it loads successfully, don;t matter how many times im trying to reload it. But when a bunch of files are loaded at one time - some random of them gets aborted. So it is happening only when a lot of files loading, when one or even 3-5 - all files loads fine
Any ideas?
Thanks
I am a little gun shy about asking questions as they have been voted down, but this was is driving me crazy. I can see from all of the Serial port event handler questions that this is a popular subject. After much effort, I got the following code working:
public void serialEvent(SerialPortEvent evt) {
if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
rdata = (byte) comIn.read();
line_buffer[line_ptr++] = rdata;
data_available = true;
// System.out.print((byte)rdata);
if( rdata == '\n') {
line_available = true;
}
}
catch (Exception e) {
System.out.print("Failed to read data. (" + e.toString() );
}
}
}
I say that it is working because if I uncomment the print, I see the data that I am expecting. I have also set breakpoints on the lines that set the data_available and the line available flags and they occur.
I am trying to communicate with this code with the following:
// Code that requests data to be send back
// Code that inserts a delay for data to be received
while( comm.line_avaiable() == false ) { }
for(int j=0;j< comm.line_ptr; j++) {
System.out.print( (char)comm.line_buffer[j] );
}
This code is to wait for data_available and then print the line of data received. With the code as shown, the while loop never gets data_available. Not only that, the event handler does not get any events. No data is echoed (with comment removed) and a break point is never hit.
IF i comment out the while loop that waits for data_available (and add the delays for the data to be received since we are running without a handshake, the data is received just fine. The event handler does hit break points if set and can echo data.
How can polling the line_available flag break the event handler?
I've been searching for four hours and this is driving me nuts. I'm going to try keeping this short, if you need more information/code ask and I'll edit.
So I have an Android client that connects to a server using PrintWriter and BufferedReader. The way it works is it starts a new ASyncTask() to load the connection. When the connection is made, it sends a "Join" message to the server, and then loads a listen thread that has a while loop waiting for UserInput.readLine() != null, and once broken it returns a string that runs a process function that takes the string and does it's action, and reloads the listen task.
//Listener thread
class listen extends AsyncTask<Integer, Integer, Void> {
#Override
protected Void doInBackground(Integer... params) {
//Disconnect variable that's only turned true on backpress
if (!disconnect) {
try {
message = Connection.listen(); //socket object
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// async task finished
if (!disconnect) {
say("INCOMMING"); //easy-made function for Toast
input(message);
}
}
}
and in that Connection:
public String listen() throws IOException {
String userInput;
while ((userInput = in.readLine()) != null) {
}
return userInput;
}
Now in my server java app, I have a thread that loads up other connection threads into an ArrayList and acts as a headquarters to dispatch messages to all child clients
In my connection:
while ((inputLine = in.readLine()) != null) {
//Tells HQ to process string, with id being who it's coming from
hq.Process(id, inputLine);
if (!connected)
break;
}
in HQ object:
public void Process(int id, String str) {
String[] msg = str.split(","); //split message
String send = " "; //string I print to console
if (msg[0].equals("join")) {
send = msg[1] + " has joined!";
parent.seats[cnew.get(id).seat] = id;
cnew.get(id).sendData();
System.out.println(id);
}
And after join, the HQ tells that connection to send that player's information to the phone
public void sendData() {
out.println("chips," + chips); // Update chip count
//give player his cards
out.println("card," + hq.parent.gameCards.getCard(10) + ","
+ hq.parent.gameCards.getCard(11));
//a cry for help to get some output on the phone
out.println("error,SAY THIS");
// out.flush(); //commented out because it didn't help at all
System.out.println("sending id " + id); //debug checker (ignore this)
}
My problem is, it worked when I connected four phones and they all sent toasts to each other.
But as soon as I changed it to send back data as soon as the player joins, I'm not getting a response in Android at all.
I can't figure out why it's not working. On server side, it's going through everything (Checked with system.prints). The connection IS made, and when I click buttons on the phone the Server is outputting it's responses. But the phone is not receiving anything -- I still don't know if the server is failing to send or the phone is failing to read. Can you see anything in the code that may be causing this? Need to see more? Or have any tips on how to debug the connection status? The listen() task is never finishing it's execution anymore.
UPDATE: So I figured out it's probably to do with my while() loop on android side, doh, probably never breaking. Stupid mistake. But I tried to add this as a tester, and still nothing:
public String listen() throws IOException {
String userInput;
while ((userInput = in.readLine()) != null) {
if (userInput.length() > 2)
break;
}
return userInput;
}
UPDATE: Next desperate update -
When I hit "back" (which sends quit msg to server that closes connection, and calls out.close and the rest.close) then I get a never ending loop of "MSG" Toast's -- The Toast that I put when an input is recognized. Is a out.close causing a block?
So it turns out, println on the server's side wasn't printing a new line -- adding + "\n" at the end of the server's messages made it go through. Why? I don't know..