Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Client Socket Problem

Posted on 2006-05-02
17
Medium Priority
?
378 Views
Last Modified: 2010-03-31
Hi to everyone:
I have been making a client socket program but it seems to work just sometimes and others doesn't.
The Client Socket is in Java, and the server in C#.
I'm not sure about if the problem is in the client or in the server, but anyway the client code looks like this, does anyone look any problem with this code????
Thanks in advance


package extended.TestPackage;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;

public class MyClientClass
{

    public String[] SendMsgToServer(String pstr)
    {
            String astr[] = new String[1000];
            if(pstr.compareTo(" CLOSE") != 0)
        {            
                  String str = "";
                  String tmp = "";
                  String tmp2 = "";
                  int intExito = 0;
                  boolean done = false;
                  int intContadorIntentos = 0;
                  Socket s = null;
                  //PrintWriter out = null;
                  BufferedReader in = null;
            
                  DataOutputStream out = null;
                  DataInputStream is = null;
       
                  String strMessageToServer = pstr;
                  Integer integ = new Integer(strMessageToServer.length());
                  strMessageToServer = integ.toString() + strMessageToServer;
                  try
                  {
                      in = new BufferedReader(new FileReader("foldertest\\innerfolder\\ip.txt"));
                      tmp = in.readLine();
                      try
                      {
                          while(!done)
                          {

                              s = new Socket(tmp, 9000);
                        
                              out = new DataOutputStream(s.getOutputStream());
                              is = new DataInputStream(s.getInputStream());
                        
                              if(s != null && out != null && in != null)
                                  try
                                  {  
                                      System.out.println(strMessageToServer);
                                  out.writeBytes(strMessageToServer);
                                      int indice = 0;
                                      Thread.sleep(250);
                                      str = is.readLine();
                                  System.out.println("Msg Received = " + str);
                                      try
                                      {
                                          Integer count = new Integer(str);
                                          for(int contador = count.intValue(); contador > 0;)
                                          {
                                              str = is.readLine();
                                        System.out.println("Received " + contador + " =" + str);
                                              astr[indice] = new String(str);
                                              contador--;
                                              indice++;
                                          }

                                          done = true;
                                        System.out.println("Cleaning Socket");
                                    out.flush();
                                    out.close();
                                    is.close();
                                    s.close();
                                      }
                                      catch(NumberFormatException e)
                                      {
                                          System.out.println("fail to connect to server trying again...");
                                      }                                                                                
                                  }
                                  catch(UnknownHostException e)
                                  {
                                      System.err.println("Unknown host : " + e);
                                  }
                                  catch(InterruptedIOException e)
                                  {
                                      System.err.println("Connection time out...");
                                  }
                                  catch(Exception e)
                                  {
                                      e.printStackTrace();
                                      System.err.println("~Error  " + e);
                                  }
                          }
                      }
                      catch(UnknownHostException e)
                      {
                          System.err.println("host desconocido: " + tmp);
                      }
                      catch(IOException e)
                      {
                          System.err.println("Cant get I/O for connection: " + tmp);
                          System.err.println("IOException:  " + e);
                      }
                  }
                  catch(IOException e)
                  {
                      System.out.println("Cant find ip.txt file = " + tmp);
                  }
            }
        return astr;
    }

    public CSock()
    {
    }
}
0
Comment
Question by:aponcealbuerne
  • 8
  • 4
  • 3
  • +1
17 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 2000 total points
ID: 16587814
You should be using BufferedReader and PrintWriter on your socket's streams and probably should not be opening a new Socket inside the loop
0
 
LVL 11

Expert Comment

by:WelkinMaze
ID: 16587837
Hi,
what happens in the cases it does not work?
btw. Are you sure that in pstr.compareTo(" CLOSE") the string value must be with space before CLOSE?
0
 
LVL 4

Author Comment

by:aponcealbuerne
ID: 16587996
About the " CLOSE" with the space,  yes i'm sure that's correct.

About using BufferedReader and PrintWriter, well my code was with that befor and i recently change it to the Streams ( I'm just testing them because I can't find the problem)

But what about Open a new Socket in the loop is that incorrect. I did that in order to retry connection in case of the server is down. So what should i do instead of that?
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 4

Author Comment

by:aponcealbuerne
ID: 16588032

O sorry and in the cases that it does not work. The problem is actually in the data received in the server.
I did the server also and I can debug it and instead of receving the complete string is receiving just the fist byte (i think)
a normal message to server looks like 13 action1188790

where 13 is the lenght of data and the rest is the data.
0
 
LVL 11

Expert Comment

by:WelkinMaze
ID: 16588034
Just open the socket once before the loop.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 16588065
Your strings should be sent using the following code

PrintWriter out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()), true);

out.println("helloworld");
0
 
LVL 4

Author Comment

by:aponcealbuerne
ID: 16588069
OK i'll try that, but if i do that, is there any case to have a loop here??? I mean I just want to send a short string and receive the answer. And if the server is down, isn't any other try to send the message would fail if i don't open the socket again????
0
 
LVL 4

Author Comment

by:aponcealbuerne
ID: 16588081
CEHJ about the PrintWriter, i did in that way before and the problem was the same
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 16588132
Shouldn't be
0
 
LVL 4

Author Comment

by:aponcealbuerne
ID: 16588356
Ok let me try and I let you know thanks
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16588363
>> PrintWriter out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()), true);

I use: PrintWriter out = new PrintWriter ( s.getOutputStream(), true ) ;

What do you have at the C# side for receiving the data? Make sure you try to read first and then check if more data is available instead of checking if data is available and then reading. Meaning:

NetworkStream ns = new NetworkStream ( socket ) ;
MemoryStream ms = new MemoryStream () ;
do
  ms.WriteByte ( ns.ReadByte () ) ; // read first
while ( ns.DataAvailable ) ; // check if more data is there - if yes, read again

If you do while ( ns.DataAvailable ) ms.WriteByte ( ns.ReadByte () ) ; you are likely to get stuck in some cases where data has not yet reached but is still on its way - because then ns.DataAvailable will return false and you will never read anything.
0
 
LVL 4

Author Comment

by:aponcealbuerne
ID: 16588465
Well yes in the C# side I do Read before checking if it's more data,
Actually i do someting like:

 public static void AcceptCallback(IAsyncResult ar) {
        // Signal the main thread to continue.
        allDone.Set();

        // Get the socket that handles the client request.
        Socket listener = (Socket) ar.AsyncState;
        Socket handler = listener.EndAccept(ar);

        // Create the state object.
        StateObject state = new StateObject();
        state.workSocket = handler;
        handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
            new AsyncCallback(ReadCallback), state);
    }


public static void ReadCallback(IAsyncResult ar) {
        String content = String.Empty;
       
        // Retrieve the state object and the handler socket
        // from the asynchronous state object.
        StateObject state = (StateObject) ar.AsyncState;
        Socket handler = state.workSocket;

        // Read data from the client socket.
        int bytesRead = handler.EndReceive(ar);

        if (bytesRead > 0) {
            ........
this is like an example in MSDN
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16588497
Can you try doing a simple synchronous receive instead of making it asynchronous? Does it work properly with a C# client?
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16588503
Try it the way I showed in my earlier example.
0
 
LVL 4

Author Comment

by:aponcealbuerne
ID: 16588561
Ok let me try, and I let you know, it's only that i don't have the environment here I will try at night. Thank you very much.
0
 
LVL 4

Author Comment

by:aponcealbuerne
ID: 16598616
Thanks a lot to everyone.

CEHJ  i just open the socket before the while and i used the BufferedReader and PrintWriter and  it works just fine.

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 16598807
:-)
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses
Course of the Month11 days, 4 hours left to enroll

571 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question