J2ME socket connection - sockets

I'm trying to implement a socket connection in my J2ME device. However I'm having some issues.
1- Sometimes the socket connection would just hang-up. I'd send a request, the server would get it and reply back but the response is never read by the client.
2- No timeout on socket: When the connection hangs, I'm forced to wait the whole 1 minute default timeout before I'm able to go out of the connection attempt. I've tried setting a timedTask to cancel/kill the thread executing the connection but I've had no success.
Any suggestions as to 1- why this could be happening (1) and how to properly implement a custom timeout for a j2me socket connection (2).
Thanks in advance,
Oscar
SOCKET Connection
String reply = "";
int ch;
try {
String name = "socket://" + socketIp + ":" + socketPort;
request = "request to socket";
socket = (SocketConnection)Connector.open(name, Connector.READ_WRITE, true);
os = socket.openOutputStream();
os.write(request.getBytes());
is = socket.openInputStream();
while( true) {
ch = is.read();
if(ch == -1) break;
if(ch < 0 && ch != -1){
break;
}
reply += (char) ch;
if(ch == '?'){
break;
}
}
socketReply(GlobalFunctions.Split(reply, "|"));
} catch (IOException ex){
socketError("Error: " + ex);
} catch (NullPointerException ex){
socketError("Error: " + ex);
} catch (ArrayIndexOutOfBoundsException ex){
socketError("Error: " + ex);
} catch (StringIndexOutOfBoundsException ex){
socketError("Error: " + ex);
} catch (Exception ex){
socketError("Error: " + ex);
} finally {
try {
// Close open streams and the socket
is.close();
os.close();
socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
TIMED TASK (For custom timeOut)
TimerTask timerTask = new TimerTask(){
public final void run()
{
try {
renderBack(displayIndex);
errorDialog(0);
is.close();
os.close();
socket.close();
t.interrupt(); //Thread running the whole connection process
} catch (IOException ex) {
ex.printStackTrace();
}
}
};
int timeOut = 20000;
timer = new Timer();
timer.schedule(timerTask, timeOut);
The timed task would work, meaning, it'd "execute" the timed tasks (at least the display change) but still the socket default timeout would be running because after 1 minute it'd throw me the "TimeOut" exception.

Related

When I close the socket,the usage of memory higher than I don't close this

I want to check the backends' healthy conditon, if a backend is dead, i will deactive this backend.
I use a ThreadPool to start a thread, ping my backend using the ip + port, per 10s.
By using Socket class, I don't close the socket at first.
Socket socket = new Socket();
InetSocketAddress address = new InetSocketAddress(domain, port);
try {
socket.connect(address, 3000);
if (socket.isConnected()) {
successCount++;
}
} catch (IOException e) {
e.printStackTrace();
}
Then I close the socket.
Socket socket = new Socket();
InetSocketAddress address = new InetSocketAddress(domain, port);
try {
socket.connect(address, 3000);
if (socket.isConnected()) {
successCount++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I want to find the diffence between this conditon in usage of memory.
I use the jconsole to display the usage of memory.
But I find if i close the socket, the usage of memory is higher than i don't close it.
This is the picture about the memory. I want to know why about this.
enter image description here
private void backendHealthCheck() {
Map<String, Boolean> backendHealthMap = new ConcurrentHashMap<>();
List<ProxyBackendConfiguration> allBackends = gatewayBackendManager.getAllBackends();
for (ProxyBackendConfiguration backend : allBackends) {
String backendName = backend.getName();
Boolean backendStatus = gatewayBackendManager.getBackendStatus(backendName);
log.debug("[{}] 对应的后端状态为 [{}]", backendName, backendStatus);
backendHealthMap.put(backendName, backendStatus);
}
scheduledExecutorService.scheduleWithFixedDelay(
() -> {
log.info("Check the backend's healthy condition");
List<ProxyBackendConfiguration> backends = gatewayBackendManager.getAllBackends();
for (ProxyBackendConfiguration backend : backends) {
int successCount = 0;
String domain = backend.getProxyTo().substring(8, 36);
int port = Integer.parseInt(backend.getProxyTo().substring(37, 41));
String backendName = backend.getName();
for (int i = 0; i < 7; i++) {
Socket socket = new Socket();
InetSocketAddress address = new InetSocketAddress(domain, port);
try {
socket.connect(address, 3000);
if (socket.isConnected()) {
successCount++;
}
} catch (IOException e) {
e.printStackTrace();
}
if (successCount >= 2) {
// if the backend is active then break, else active this backend
// if this is not in map, get false active this backend
// if this backend in this map,and status is false,then active this backend
if (!backendHealthMap.getOrDefault(backendName, false)) {
gatewayBackendManager.activateBackend(backendName);
backendHealthMap.put(backendName, true);
}
break;
}
if (i == 6) {
// if this backend in map and the status is false, continue
// if this backend is not in map, get status is true,then deactive this backend
// if this backedn in map, and status is true,then deactive this backend
if (backendHealthMap.getOrDefault(backendName, true)) {
gatewayBackendManager.deactivateBackend(backendName);
backendHealthMap.put(backendName, false);
}
}
}
}
},
0,
10,
TimeUnit.SECONDS);
}

Data not completely received on the receiver side when sleep is introduced on the receiver side

I am using a file transfer application using tcp sockets. In normal scenario,when i try to send a file using the application the complete file is received, but when i put a sleep of 40 ms in between every packets received i am receiving only part of the file. I am also closing the socket immediately after the complete file is sent out to the output stream. What could be the possible reason why i am not receiving the complete file?. Below is the code for the sender side and receiver side. Thanks in advance.
/////////////////////////Sender Side////////////////////////////
bytesLeft = fileSize;
while(bytesLeft > 0)
{
try
{
bytesRead = fileInpStream.read(buffer, 0, BUFFERSIZE);
outStream.write(Arrays.copyOfRange(buffer, 0, bytesRead));
}
catch (IOException e)
{
try
{
fileInpStream.close();
}
catch (IOException e1)
{
Log.i(LOGC, "Error " + e1.getMessage());
e1.printStackTrace();
disconnect();
return;
}
}
bytesLeft -= bytesRead;
if (bytesLeft < 1)
{
try
{
fileInpStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
//Closing the socket immediately after all the data are sent to out stream.
try
{
socket.close();
}
catch (StcException e)
{
e.printStackTrace();
}
/////////////////Receiver Side//////////////////////////
bytesLeft = filesize;
while (bytesLeft > 0)
{
try
{
if (bytesLeft < BUFFERSIZE)
readAmount = (int) bytesLeft;
bytesRead = inpstream.read(buf, 0, readAmount);
if (bytesRead < 1)
{
fileoutputstream.close();
}
fileoutputstream.write(Arrays.copyOfRange(buf, 0,bytesRead));
bytesLeft -= bytesRead;
//Including a sleep of 40 ms or more doesnt completely receive the data.
//try{ sleep(40) } catch(Exception e){ }
if (bytesLeft == 0)
{
fileoutputstream.close();
}
}
catch (IOException e)
{
try
{
fileoutputstream.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
You don't need the sleep in the first place. Leave it out. It is just literally a waste of time. Your code is several times as complex as it needs to be, and probably masking a few lurking bugs. This:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
out.close();
is sufficient, at both ends.

How to get Parrot AR.Drone 2.0 fly? State Error occurred

I am trying to implement javadrone (AR.Drone Java API) in my project. However, it was occurred state changed error when I compile my java code and try to fly it. I was able to send command to AR.Drone and fly for the first time. After successfully take off for the first time,it won't take off again due to "state changed" error. I have no idea what went wrong in my code. Please help me out. Thanks! There are 3 files that are required in this project. My java file(arDroneFrame.java),NavData.java(from javadrone), and ARDrone.java(from javadrone).The The main java file: arDroneFrame.java. When I press the TakeOff button, it should make AR.Drone fly and land afterwards.
In my arDroneFrame.java,
private void jButtonTakeOffActionPerformed(java.awt.event.ActionEvent evt) {
com.codeminders.ardrone.ARDrone drone;
try{
drone = new com.codeminders.ardrone.ARDrone();
drone.connect();
drone.clearEmergencySignal();
// Wait until drone is ready
drone.waitForReady(CONNECT_TIMEOUT);
// do TRIM operation
drone.trim();
// Take off
System.err.println("Taking off");
drone.takeOff();
// Fly a little :)
Thread.sleep(5000);
//Land
System.err.println("Landing");
drone.land();
// Give it some time to land
Thread.sleep(2000);
// Disconnect from the done
drone.disconnect();
} catch (UnknownHostException ex) {
Logger.getLogger(arDroneFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(arDroneFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(arDroneFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
In ARDrone.java, I had commented out some java coding.This is because only when I comment out those java code, it can only works. If I uncomment them, my program will be stuck there (no respond at all).
public void waitForReady(long how_long) throws IOException
{
/*long since = System.currentTimeMillis();
synchronized(state_mutex)
{
while(true)
{
if((System.currentTimeMillis() - since) >= how_long)
{
try
{
disconnect();
} catch(IOException e)
{
}
// Timeout, too late
throw new IOException("Timeout connecting to ARDrone");
} else if(state == State.DEMO)
{
return; // OK! We are now connected
} else if(state == State.ERROR || state == State.DISCONNECTED)
{
throw new IOException("Connection Error");
}
long p = Math.min(how_long - (System.currentTimeMillis() - since), how_long);
if(p > 0)
{
try
{
state_mutex.wait(p);
} catch(InterruptedException e)
{
// Ignore
}
}
}
}*/
while(state == State.DEMO)
{
System.out.println("Changed to DEMO !");
return; // OK! We are now connected
}
}
Program Output:
126 [Thread-7] DEBUG ardrone.ARDrone - State changed from TAKING_OFF to ERROR with exception
java.lang.NullPointerException
at com.codeminders.ardrone.NavData$FlyingState.fromControlState(NavData.java:58)
at com.codeminders.ardrone.NavData.getFlyingState(NavData.java:622)
at com.codeminders.ardrone.ARDrone.navDataReceived(ARDrone.java:431)
at com.codeminders.ardrone.NavDataReader.run(NavDataReader.java:92)
at java.lang.Thread.run(Thread.java:745)

Connections going into close_wait

Since so many days we are facing the problem of close_wait connection..My doubt was that not all the connections with that particular server are going into close wait.If it would have been problem with the code then this problem should be with every connection I am making with the server.Destination server is apache server and source server is glassfish . I have also added header for closing connection according to this article.http://www.michaelprivat.com/?p=63 But no luck I am posting code which I have used for making connection with the target server .Is there any problem while making connection?
public String Consumer(String userId, String Type) throws IOException {
CloseableHttpClient hc = HttpClients.createDefault();
try {
String response = null;
ResponseHandler<String> res = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("http://IP and port of th target server/PolicyService.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userId", userId));
nameValuePairs.add(new BasicNameValuePair("Type", Type));
nameValuePairs.add(new BasicNameValuePair("token", Token));
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
postMethod.addHeader("Connection", "close");
response = hc.execute(postMethod, res);
return response;
} catch (HttpResponseException g) {
logger.error("Exception occurred of type: " , g);
return "";
} catch (UnsupportedEncodingException e) {
logger.error("Exception occurred of type: " , e);
return "";
} catch (ClientProtocolException e) {
logger.error("Exception occurred of type: " , e);
return "";
} catch (IOException e) {
logger.error("Exception occurred of type: " , e);
return "";
}
finally{
hc.close();
}
}
everytime I have to restart server to flush this connections .Any sugestions?

Why I am receiving null in my output?

I want to send a message to my computer from my phone using TCP..My computer is the server and my phone is the client. I am able to send a message from my phone to my computer but in the output, I get null characters ..
I paste my codes below;;
Client ::
public void startApp() {
try {
// establish a socket connection with remote server
streamConnection =
(StreamConnection) Connector.open(connectString);
// create DataOuputStream on top of the socket connection
outputStream = streamConnection.openOutputStream();
dataOutputStream = new DataOutputStream(outputStream);
// send the HTTP request
dataOutputStream.writeChars("Hello");
dataOutputStream.flush();
// create DataInputStream on top of the socket connection
inputStream = streamConnection.openInputStream();
dataInputStream = new DataInputStream(inputStream);
// retrieve the contents of the requested page from Web server
String test="";
int inputChar;
System.out.println("Entering read...........");
while ( (inputChar = dataInputStream.read()) != -1) {
// test=test+((char)inputShar);
results.append((char) inputChar);
}
System.out.println("Leaving read...........");
// display the page contents on the phone screen
//System.out.println(" Result are "+results.toString());
System.out.println(" ");
resultField = new StringItem(null, results.toString());
System.out.println("Client says "+resultField);
resultScreen.append(resultField);
myDisplay.setCurrent(resultScreen);
} catch (IOException e) {
System.err.println("Exception caught:" + e);
} finally {
// free up I/O streams and close the socket connection
try {
if (dataInputStream != null)
dataInputStream.close();
} catch (Exception ignored) {}
try {
if (dataOutputStream != null)
dataOutputStream.close();
} catch (Exception ignored) {}
try {
if (outputStream != null)
outputStream.close();
} catch (Exception ignored) {}
try {
if (inputStream != null)
inputStream.close();
} catch (Exception ignored) {}
try {
if (streamConnection != null)
streamConnection.close();
} catch (Exception ignored) {}
}
}
My server :
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try{
ServerSocket sck=new ServerSocket(880);
Socket client=sck.accept();
InputStream inp= client.getInputStream();
int i;
OutputStream out=client.getOutputStream();
out.write("Testing ".getBytes());
System.out.println("Server has responded ");
String str="";
while((i=inp.read())!=-1){
str=str+((char) i);
System.out.println("USer says "+ str);
}
}
catch(Exception e){
System.out.println("Error "+e);
}
}
}
My output for the server ;;
Server has responded
USer says null H
User says null H null
User says null H null e
etc etc
I am not supposed to get this null character,why I am getting it??
Another thing, my server is writing to the stream but the client is not able to receive that,why is that?Do I need to use a separate thread for that?
Thanks in adv
I would guess that isn't your real code, and that your real code initialized str to null.