0

For the chat program in android side I am sending message via DataInput stream as

Socket sck = new Socket();
sck.connect(new InetAddress("192.168.1.91",1500),2000);

if(sck.isConnected())
{
    DataOutputStream os = new DataOutputStream(sck.getOutputStream());
    os.writeUTf(msg);
    System.out.println("Message sent");
}

and on the Server side My code is

ServerSocket serv = new ServerSocket(1500);
Socket sock = serv.accept();
DataInputStream is = new DataInputStream(sock.getInputStream);    

String ans = is.readUTF();
System.out.println("Got"+ans);

But on server side it seems it does not received anything and still waiting for the message. But on client side It shows message sent.

Here is my full code.

package in.prasilabs.eagleeye;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class EagleClient extends Thread
{

    public int ret = 0;
    private String ip;
    private int port;
    private Socket sck;
    private boolean estb = false;
    private DataInputStream is;
    private DataOutputStream os;
    private String rmsg = null;
    private String msg;
    private String username;
    private String password;

    public String reply;

    Data dt = new Data();

    public EagleClient() 
    {

    }
    public EagleClient(String ip, int port, String username, String password)
    {
        this.ip = ip;
        this.port = port;
        this.username = username;
        this.password = password;
    }

    public void run()
    {
        establish();
        if(estb == true)
        {
            sendInfo(username,password);
        }

    }
    public void establish()
    {
        int time_out = 2000;
        try 
        {
            System.out.println("trying to connect");
            sck = new Socket();
            sck.connect(new InetSocketAddress(dt.getIp(),dt.getServerPort()),time_out);
            estb = true;
            System.out.println("Established");

        }
        catch (UnknownHostException e) 
        {
            ret =0;
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            ret = 0;
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(estb == true)
        {
            try {
                is = new DataInputStream(sck.getInputStream());
                os = new DataOutputStream(sck.getOutputStream());
                dt.setOS(os);
                dt.setIS(is);
                System.out.println("Messages are ready to send");
            } catch (IOException e) 
            {
                ret = 0;
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
    public void sendInfo(String user,String password)
    {
        Data dt = new Data();
        is = dt.getIS();
        os = dt.getOS();
        String drport = Integer.toString(dt.getdrPort());
        try {
            os.writeUTF("logn");
            System.out.println("Sending user info");
            os.writeUTF(dt.getUsername());
            os.writeUTF(dt.getPassword());
            os.writeUTF(drport);
            reply = is.readUTF();
            if(reply.equals("success"))
                dt.setLoginStatus(true);
            else
                dt.setLoginStatus(false);
            System.out.println("ACk recieved");
        } catch (IOException e) {
            ret = 0;
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    public int sendMessage(String msg)
    {
        Data dt = new Data();
        os = dt.getOS();
        is = dt.getIS();
        this.msg = msg;
        try {
            os.writeUTF(msg);
            System.out.println("Client :" +msg);
            recieveMessage();
        } catch (IOException e) {
            ret = 0;
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ret;
    }
    public void recieveMessage()
    {
        try {
            System.out.println("Trying to get acknowledgement");
                sck.setSoTimeout(2000);
                rmsg = is.readUTF();
                if(rmsg.equals(msg))
                {
                    System.out.println("Ack recvd" +rmsg);
                    ret = 1;
                }
                else if(!msg.equalsIgnoreCase(rmsg))
                {
                    //sendMessage();
                    Thread.sleep(100);
                    System.out.println("Retrying");
                    rmsg = is.readUTF();
                    System.out.println("Ack recvd" +rmsg);
                    ret = 1;
                }
                else
                {
                    System.out.println("Message not recieved");
                    ret = 0;
                }
        } catch (IOException e) {
            ret = 0;
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e){
            e.printStackTrace();
        }
    }



}
user207421
  • 305,947
  • 44
  • 307
  • 483
Prasanna Anbazhagan
  • 1,693
  • 1
  • 20
  • 37
  • do you not have a while loop in your server? how do you ensure that it is always waiting for connections? – Adeeb Jan 12 '15 at 08:51
  • @Adeeb. Yes until connection is there I have a while loop at ans = is.readUTf() – Prasanna Anbazhagan Jan 12 '15 at 08:56
  • 1
    Try os.flush() after the writeUTF – laune Jan 12 '15 at 08:59
  • @laune `DataOutputStreams` don't need flushing unless they are layered over streams that do, i.e. `BufferedOutputStream`. – user207421 Jan 12 '15 at 09:06
  • 1
    `Socket.isConnected()` doesn't do what you think it does. Specifically, it doesn't test the state of the connection. It only tells you whether *you* connected *this `Socket.`* Testing it immediately afer calling `Socket.connect()` is completely pointless. It will always return `true` unless an exception is thrown, in which case the test is unreachable. – user207421 Jan 12 '15 at 09:06
  • @Prasanna I don't believe this. Either your client didn't connect or this isn't the real code. – user207421 Jan 12 '15 at 09:13
  • @EJP. I using the client as thread to initialize and calling its function/method to send particular message – Prasanna Anbazhagan Jan 12 '15 at 09:58
  • Meaningless. Is this the real code or not? If not, what is the real code? The code you've posted does not behave as described. – user207421 Jan 12 '15 at 10:00
  • @EJP. I attached the full code for the client – Prasanna Anbazhagan Jan 12 '15 at 10:02
  • Fine. Where is the Data class? And how can a *new* instance of Data possibly contain the InputStream and OutputStream that were set on a *prior* instance of Data? And what exceptions are being thrown? On the evidence here you're getting a NullPointerException in the client which you have failed to tell us about. – user207421 Jan 12 '15 at 10:14
  • @EJP. No exception are thrown. The outputstream sends messages without any exception but the inputstream still waiting. the inputstream works for a single time only. – Prasanna Anbazhagan Jan 12 '15 at 12:46
  • I repeat. Where is the `Data` class? How do you expect people to help you with your code when you don't post it all? – user207421 Jan 12 '15 at 19:01
  • I am sorry guys. It's not a problem with this. Code. .. there is some other technical mistake. Overall this one is a working code. I am sorry – Prasanna Anbazhagan Jan 15 '15 at 03:45

1 Answers1

-3

Try to use something like this:

String message = "";

while (!"end".equals(message)) {
    if (is.available() != 0) {
        message = dis.readUTF();
        System.out.println(message);
    }
}

I checked this - working. Server must be up before client will send message.

DmitryKanunnikoff
  • 2,226
  • 2
  • 22
  • 35
  • I suggested direction only. Not a complete solution. – DmitryKanunnikoff Jan 12 '15 at 09:00
  • The problem - server must print message from client. My portion of help will solve the problem. – DmitryKanunnikoff Jan 12 '15 at 09:02
  • @laune, and what is the problem in this case? Why minus? – DmitryKanunnikoff Jan 12 '15 at 09:03
  • Yes - not optimal, yes - it is bad approah, but it solves the problem in question above. I don't understand people like you. – DmitryKanunnikoff Jan 12 '15 at 09:04
  • Consider: server sends several String values, with delays in between. Client receives first message, but then available() returns 0 (server hasn't sent 2nd String yet) and the while loop just iterates and iterates and iterates all the time. Google "polling" and "active waiting for i/o". – laune Jan 12 '15 at 09:06
  • 1
    There is simply *no reason* to avoid blocking and loop needlessly when you have a blocking readUTF which *does* the waiting for you. – laune Jan 12 '15 at 09:07
  • I know! I know that this is big pressure on CPU. But I suggested direction only! Do you undestand? – DmitryKanunnikoff Jan 12 '15 at 09:08
  • This is an abuse of `available()`. It isn't a test for end of stream. See the Javadoc. It also doesn't solve the problem. It just introduces a CPU-smoking spin loop. It also doesn't cease smoking the CPU at end of stream. – user207421 Jan 12 '15 at 09:08
  • @laune You did indeed. There are few if any correct uses of `available()`, and this isn't one of them. – user207421 Jan 12 '15 at 09:10