Ahmad Al-Sanie
Ahmad Al-Sanie

Reputation: 3785

sending and recieving data through sockets in the same activity

i'm using TCP socket to send and receive data from the same socket in the same activity through client server thread, the purpose of that is to send a string to other device and that string will trigger a notification once the other device receives it then that device will replay with something like dismiss or accepted, the problem that i'm having is after sending the string the other device receives it and send the dismiss or accepted String but my divice doesn't receive that string i guess there is a problem in my ServerThread be aware that the server thread and client thread are in the same activity used as an inner classes and get called in a button. code:

ClientThread

private class ChatClientThread extends Thread {








          @Override
          public void run() {
           Socket socket = null;
           DataOutputStream dataOutputStream = null;




           try {

            socket = new Socket("192.168.0.113", 23);
            dataOutputStream = new DataOutputStream(
              socket.getOutputStream());



            dataOutputStream.writeUTF("  "+"SolveProblemOrder_2");
            dataOutputStream.flush();

            ServerThread serv =new ServerThread();
            serv.start();

           } catch (UnknownHostException e) {
            e.printStackTrace();
            final String eString = e.toString();
            TicketDetails.this.runOnUiThread(new Runnable() {

             @Override
             public void run() {
              Toast.makeText(TicketDetails.this, eString, Toast.LENGTH_LONG).show();
             }

            });
           } catch (IOException e) {
            e.printStackTrace();
            final String eString = e.toString();
            TicketDetails.this.runOnUiThread(new Runnable() {

             @Override
             public void run() {
              Toast.makeText(TicketDetails.this, eString, Toast.LENGTH_LONG).show();
             }

            });
           } finally {
            if (socket != null) {
             try {
              socket.close();
             } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
             }
            }

            if (dataOutputStream != null) {
             try {
              dataOutputStream.close();
             } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
             }
            }



            TicketDetails.this.runOnUiThread(new Runnable() {

             @Override
             public void run() {

             }

            });
           }

          }


         }

ServerThread

public class ServerThread extends Thread {

          private ServerSocket serverSocket;
          private Socket clientSocket;


          public void run(){

            try{
              // Open a server socket listening on port 23
              InetAddress addr = InetAddress.getByName(getLocalIpAddress());
              serverSocket = new ServerSocket(23, 0,addr);
              try{
              clientSocket = serverSocket.accept();
             DataInputStream dataInputStream = new DataInputStream(clientSocket.getInputStream());
             String newMsg = null;
             Toast.makeText(getApplicationContext(), newMsg, Toast.LENGTH_LONG).show();
              // Client established connection.
              // Create input and output streams
              while (true) {
                     if (dataInputStream.available() > 0) {
                      newMsg = dataInputStream.readUTF();
                              }

              }}catch(Exception e){
                     e.printStackTrace();
                 }
              // Perform cleanup



            } catch(Exception e) {
              // Omitting exception handling for clarity
            }
          }

          private String getLocalIpAddress() throws Exception {
            String resultIpv6 = "";
            String resultIpv4 = "";

              for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); 
                en.hasMoreElements();) {

                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); 
                    enumIpAddr.hasMoreElements();) {

                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if(!inetAddress.isLoopbackAddress()){
                      if (inetAddress instanceof Inet4Address) {
                        resultIpv4 = inetAddress.getHostAddress().toString();
                        } else if (inetAddress instanceof Inet6Address) {
                          resultIpv6 = inetAddress.getHostAddress().toString();
                        }
                    }
                }
            }
            return ((resultIpv4.length() > 0) ? resultIpv4 : resultIpv6);
          }
        }

i start those two threads in a button Click listener:

ChatClientThread chatClient=new ChatClientThread();
                        chatClient.start();
ServerThread serv =new ServerThread();
        serv.start();

if this won't work using server/client in the same activity using the same port is there any other way to listen to a socket like is there a built in listener or something like that. any help is appreciated

Upvotes: 1

Views: 2586

Answers (1)

Maria Gheorghe
Maria Gheorghe

Reputation: 629

You write to socket thru socket.getOutputStream() and you must read from InputStream of socket.getInputStream() ; You can adapt your code . Your server use InputStream from socket to read data ,so you must to do also in your client code , cause you want also to receive data not only to send.

check this out just read is is very simple.

https://systembash.com/a-simple-java-tcp-server-and-tcp-client/

See the code for reading from socket taht start with :

BufferedReader inFromClient =
               new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

and code for writing to socket:

   DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

or search google : java client server .

The ideea is that you send data to the socket outputstream and you can read it from same socket inputstream.

you see here example it read data from socket input and send data thru socket output , to server

String sentence;
  String modifiedSentence;
  BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
  Socket clientSocket = new Socket("localhost", 6789);
  DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
  BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  sentence = inFromUser.readLine();
  outToServer.writeBytes(sentence + '\n');
  modifiedSentence = inFromServer.readLine();
  System.out.println("FROM SERVER: " + modifiedSentence);
  clientSocket.close();

Upvotes: 2

Related Questions