Friday, October 25, 2013

Socket Connection in Android - Bi directional (Simple and Easy)

I have written a class for socket programming.This class can be used for creating both server and client socket.you don't have to write classes for server and client separately.

This class contains two constructors.

for Server :

SocketConnection(int Port,final Handler ReturnHandler)

Port : server port where the socket is open (default is 8080)
ReturnHandler : handler for handling the received value from client

 for Client :

SocketConnection(String ipAddress,int Port,final Handler ReturnHandler)

 ipAddress : Ipaddress of the server where the client have to connect.
ReturnHandler : handler for handling the received value from server


Functions :

ReadValues : This function is used to Read the values and do what with the received value
the Red line is where you have to change accourding to your need (I use send Empty message function and integer value). This function is called after the connection is accepted

public void ReadValues()
    {
        Thread threadRead = new Thread(new Runnable() {
           
            @Override
            public void run() {
                // TODO Auto-generated method stub
               
               
                try {
                 BufferedReader in = new BufferedReader(new InputStreamReader(m_SocClient.getInputStream()));
                String line = null;
                while ((line = in.readLine()) != null) {
                    m_ReturnHandler.sendEmptyMessage(Integer.parseInt(line));
                }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        threadRead.start();
       
    }


WriteValues : This function is used to send values to client/Server from Server/Client.I use integer as input parameter you can use any parameter


    public void WriteValues(final int Number)
    {
        Thread threadWrite = new Thread(new Runnable() {
           
            @Override
            public void run() {
                // TODO Auto-generated method stub
                if(outputValues==null)
                {
                    try {
                        outputValues = new PrintWriter(new BufferedWriter(new OutputStreamWriter(m_SocClient.getOutputStream())), true);
                       
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                outputValues.println(Number);
            }
        });
        threadWrite.start();
    }


No comments:

Post a Comment