Connections going into close_wait - sockets

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?

Related

J2ME socket connection

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.

POST over SSL/HTTPS REST Api Android is responding 400 Bad Request

In my application I want to post from my android application XML data in the remote server which is using REST service. My code is below:
String url = "api.example.com";
int port = 443;
String query = "<?xml version='1.0' encoding='UTF-8'?><request><client><name>APIappDevAccount</name><password>123456</password></client><user><name>foyzulkarim</name><password>123456</password><groupId>12345</groupId></user></request>";
Socket socket = null;
try {
socket = new Socket(url,port);
} catch (UnknownHostException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
PrintStream pw = null;
try {
pw = new PrintStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.print("POST api.example.com/rest/rest/user");
pw.print("Content-Type: application/xml");
pw.print("Content-Length:" + query.length());
pw.print(query);
System.out.println("hello foysal.");
//get result
String l = null;
String text="";
try {
while ((l=br.readLine())!=null) {
System.out.println(l);
text+=l;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.close();
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But that server is behind SSL/HTTPS protocol so i am getting the below 400 Bad Request as response.
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>400 Bad Request</title></head><body><h1>Bad Request</h1><p>Your browser sent a request that this server could not understand.<br />Reason: You're speaking plain HTTP to an SSL-enabled server port.<br />Instead use the HTTPS scheme to access this URL, please.<br /><blockquote>Hint: <b>https://api.example.com/</b></blockquote></p></body></html>
If I use SSLSocketFactory like below
SocketFactory socketFactory = SSLSocketFactory.getDefault();
Socket socket = null;
try {
socket = socketFactory.createSocket(url, port);
I got exception
javax.net.ssl.SSLException: Not trusted server certificate
java.security.cert.CertPathValidatorException: TrustAnchor for CertPath not found.
at line
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
My question is, how can i post the data over SSL from android application in my above scenario?
I guess many of us are facing this problem, so I am requesting you to give me/us some elaborated answers.Cheers.
Too many unknowns :-)
Try plain HTTP against a test server you have control over.
My hunch is it will give the same error.
You don't seem to put an empty line between the HTTP headers and body for example.
Why are you re-implementing HTTP anyway? Don't tell me there's no API or library you could use on whatever platform this is? Usually there's java.net.HttpUrlConnection, or Apache HttpClient.
Edit:
Hey, look what google brought in: http://developer.android.com/reference/android/net/http/AndroidHttpClient.html
It seems that I needed to add the TrustAnchor certificate to be able to validate the whole key chain.
I have requested about this certificate to my API Provider and they given me the web link from where I can get the certificate. [i have changed the web link for confidentiality]
https://www.example.com/library/......SSL_bundle.pem
They also told me to get try the connection via (i guess it should be executed from command prompt)
openssl s_client -connect api.example.com:443 -CAfile /root/SSL_bundle.pem
I then have to integrate the certificate into my application.
I will now try to know how can I integrate that certificate, but that discussion should be in another question.
I have done it. The code is given below.
private String executeRequest(String targetURL, final String requestMethod,
String soap_request_message_header, String soap_request_message_body) {
URL url;
HttpURLConnection connection = null;
try {
url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(requestMethod);
connection.setRequestProperty("SOAPAction",
soap_request_message_header);
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
// Send request
DataOutputStream wr = new DataOutputStream(connection
.getOutputStream());
wr.writeBytes(soap_request_message_body);
wr.flush();
wr.close();
// Get Response
InputStream is;
final int responseCode = connection.getResponseCode();
Log.i("response", "code=" + responseCode);
if (responseCode <= 400) {
is = connection.getInputStream();
} else {
/* error from server */
is = connection.getErrorStream();
}
// is= connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
Log.i("response", "" + response.toString());
return response.toString();
} catch (Exception e) {
Log.e("error https", "", e);
return e.getMessage();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}

Java socket programming problem

Hey,
I am trying to run this socket programming code.
This is the code on the server side -
package sockettest;
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(139);
}
catch (IOException e)
{
System.err.println("not able to listen on port");
System.exit(1);
}
Socket clientSocket = null;
try
{
clientSocket = serverSocket.accept();
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); // Out is Outputstream is used to write to the Client .
BufferedReader in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream())); // in is used to read the Client's input.
String inputLine, outputLine;
out.println("Hey! . Who are you?"); // Writes to client as "Hey! . Who are you?"
while ((inputLine = in.readLine()) != null)
{
// Reads the input from the Client. if it is "bye" the program ends.
if (inputLine.equalsIgnoreCase("Bye"))
{
out.println("Bye");
break;
}
else
{
out.println("Hello Mr. " + inputLine);
}
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
This is the code running on the client side -
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String[] args) throws IOException {
Socket kkSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try
{
kkSocket = new Socket("192.168.2.3", 139);
out = new PrintWriter(kkSocket.getOutputStream(), true); // Out may be used to write to server from the client
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream())); // in will be used to read the lines sent by the Server.
}
catch (UnknownHostException e)
{
System.err.println("Unidentified host.");
System.exit(1);
}
catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection to.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromClient;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Bye"))
break;
fromClient = stdIn.readLine();
if (fromClient != null) {
System.out.println("Client: " + fromClient);
out.println(fromClient);
}
}
out.close();
in.close();
stdIn.close();
kkSocket.close();
}
}
I'm running the codes on eclipse in both the client and the server side. Using netstat -an command in cmd prompt, i can see that a connection has been established between the client and the server but i cannot communicate and eclipse is not showing any output too. What seems to be wrong??
You haven't told us what the problem is. However, from a cursory glance at your code, I would advise against listening on port 139 as this is already used by NetBios under Windows and may cause a conflict.
also your Server code is missing
the initialization of inputLine,
e.g
String inputline = "";
before the while loop
keep in mind that Socket's are blocked if you read or write...
your client is reading all the time because it waits for every information on the server
until it is null
and your server also reads all the time and is waiting for any input..
so as long as server and client are waiting for input, no one will receive any data.
try to think of a protocol to communicate between the server and the client.
e.g
Sever to Client: Hello Who are you?
Client receives Data and replies: Client
Server receives Information: You Are now authorized, what ya gonna do?
and so on ^^
also out.flush() is needed to send a message

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.

linking my applet to a server dirctory to recieve or save a file from there?

I' m looking for a code to save the files created in a applet normally text files i want to save them on a server directory how can i do so.
Here is an example of how to send a String. In fact any Object can be sent this method so long as it's serializable and the same version of the Object exists on both the applet and the servlet.
To send from the applet
public void sendSomeString(String someString) {
ObjectOutputStream request = null;
try {
URL servletURL = new URL(getCodeBase().getProtocol(),
getCodeBase().getHost(),
getCodeBase().getPort(),
"/servletName");
// open the connection
URLConnection con = servletURL.openConnection();
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/octet-stream");
// send the data
request =
new ObjectOutputStream(
new BufferedOutputStream(con.getOutputStream()));
request.writeObject(someString);
request.flush();
// performs the connection
new ObjectInputStream(new BufferedInputStream(con.getInputStream()));
} catch (Exception e) {
System.err.println("" + e);
} finally {
if (request != null) {
try {
request.close();
} catch (Exception e) {
System.err.println("" + e);
};
}
}
}
To retrieve on the server side
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
try {
// get the input stream
ObjectInputStream inputStream = new ObjectInputStream(
new BufferedInputStream(request.getInputStream()));
String someString = (String)inputStream.readObject();
ObjectOutputStream oos = new ObjectOutputStream(
new BufferedOutputStream(response.getOutputStream()));
oos.flush();
// handle someString....
} catch (SocketException e) {
// ignored, occurs when connection is terminated
} catch (IOException e) {
// ignored, occurs when connection is terminated
} catch (Exception e) {
log.error("Exception", e);
}
}
No one is going to hand you this on a plate. You have to write code in your applet to make a socket connection back to your server and send the data. One way to approach this is to push the data via HTTP, and use a library such as commons-httpclient. That requires your server to handle the appropriate HTTP verb.
There are many other options, and the right one will depend on the fine details of the problem you are trying to solve.