Showing posts with label Networking. Show all posts
Showing posts with label Networking. Show all posts

Sunday, April 3, 2016

X-Files ; Sockets 3rd and last ; TESLA car


Finally this is last of Sockets, in this I am attaching the zip file of Server and Client Code.

Server will open a server socket and listen to client connection.

Client will open a connection with Server and wait for any input data.

server will send "Hello from Server" to client.

The code is very basic, there is no extra line of code which is not required. NOTE : this app will have problems, as optimized coding is not done.


Also UI-wise,  Server has just one text box, in which Server IP address is shown.

Client has two text-box , in one we will input the Server IP address in other Text Box the message send by server will be displayed.


Also you will see implementation of ASYNC task at server side. It is required to create connection and wait for CLIENT request. First I thought that is not required, but my UI was unresponsive without implementing it.

Reason : socket.accept() call is blocking call, until some client doesn't request connection , further code execution will not take place.

That's it amigo's.


Coming to second part, I was watching X-files,  it's not so good. But there was a question which came to my mind.

1) Is apeing greater than pure genius ?


Now I always wanted to do socket programming, but my inherent nature doesn't allow me to understand other people code. My brain just shuts down, when some one tells me how something worked.

I like to learn by my own. But what I have seen, learning by your own , discovering what other have discovered , reinventing the wheel should be attributed to DUMB people.

The very foundation of human society is build on SHARING.We learn from other experience, other mistakes, other success and this learning shortens next generation re-learning curve.

Now I was talking with my roommate, and he was telling me about TELSA car. What was beautiful in that CAR is that they have MACHINE LEARNING.  So if you are taking your car to some place and say it is hilly terrain. You have some sharp turn and did skid, the next time any TELSA car goes on that route will know what speed is dangerous on that turn.



Wow !!!!

Same way , what I coded in socket programming was learning from the 3-4 applications made by others.

But sometimes I feel what if everything we are learning is not natural but artifical ?

Like the matrix movie, where they show everyone is kept in a chamber and their brains are feed with real world image.

Telling even LIES a hundred times, makes it a truth. This is how we humans are.

What if the CASTE, COLOR, COUNTRIES we have created are in interest of FEW people. And we are told/teached whatever they want.

So it also raises one interesting question :


Do we want to live in harsh reality or beautiful truth ? 
`

It seems there is no option of attaching files to blogspot, so here is link for drive

https://drive.google.com/folderview?id=0B6HF3JcgAklva0VsSWIzZDZldG8&usp=sharing

Saturday, April 2, 2016

Sockets : Part 2


Only I know how tuf it is to write the second part. Not because of technical things, but simply because of my nature. I am very curious by nature , but flicking. I started SOCKETS article to make an app, then once I knew how it can be done, I start becoming disinterested.

But PROCRASTINATION , is not going to take me anywhere. So even if universe ends today, I have to complete this before it.

So lets start directly.

Now as I see right now, maybe this article might not end with Article 2, but spill further into one more article.

Now I will try to have code + theory at same time, else interest goes away. As we have seen in last article knowing just SOCKET API/functions are not enuf, we need to know also about OS. So in this article we will see threads and async task, as per our requirement. 

> Layout of our Program.  If anyone has used Android Studio or Eclispe before for Android application they know about

  Manifest.xml , Layour.xml , .java files. We will not see those in here, possibly I give put snapshot of those in my next article.

Now in Android, when we make application, we divide them into Activities, Each Activity which we create has a UI part, which is govern by .xml file  and .java part which has the code.

So in this article we will focus on code part.

So in both the Server and Client application, we will have  1 activity which will be main activity

 Server Main activity will create a Server class which will have function to open socket, accept client socket and send data to client. Server Class will be defined in separate .Java file, we will not need activity for this as we don't need UI for this.

Client Main activity will create a Client class which will have function to create socket, and once connection is created listen to what Server is sending and display it on UI.  Note Client class will be defined in Client.java file,  no activity is needed for it. Display will be done on the Clint Main activity UI.

Now below picture is for Server App in eclipse,

You can see Mainactivity.java which will have code for MAIN activity. Since it is activity it will have a corresponding xml file, which is activity_main.xml which will have UI.

Then the whole server code will go into Server.Java file.  In this article we will see only Server.java and Client.Java.

Then there is a AndroidManifest.xml file which governs the properties of Android app, we will see its use at the end.







So  we have got enuf skeleton of our app,  we will now start with to put flesh and muscles to it.


Now first starting with Server app, Server app has to accept Client socket request and also send data to existing clients.  So we need to have two simultaneous operation ongoing to support this.
So we will need threads. THREADS helps to run task in parallel. In java already THREAD class is present, we need to extend that class to get the work done.

Code wise

  private class ServerSendData extends Thread {    // here ServerSendData is our class in which we will have code for sending data to client and it is extending the thread class, so our class ServerSendData will run as totally independent body with respect to other part of Server program. 


> Now get started

The below code is psuedo-code for understanding , main code files I will try to upload. 


private class Server {

int port_no = 8080;

void opensocket() {

  ServerSocket serverSocket  = new ServerSocket(port_no);   // SERVER socket is created

 Socket socket_c = serverSocket.accept();  // this will accept only ONE  client connections.

  ServerSendData ssd = new ServerSendData(socket_c);  // Here we have create another class to                                                            send data
   ssd.run();   // we called the other class function
   
}

 private class ServerSendData extends Thread {   // this will run indepently to above code

       string msg = " I am server";
       socket client_socket;
     
     ServerSendData(socket clientsocket)
      {
            client_socket = clientsocket;
      }

     public void run()
    {
           OutputStream outputStream = client_socket.getOutputStream();// Here we are getting outstream                                                                    of socket
    PrintStream printStream = new PrintStream(outputStream); // printstream will put all message                                                               pass to it to outstream
    printStream.print(msg);   // Finally we have send message
    }
      
}
}

The above code shows how to achieve functionality of sending  data from Server.  Below we will see code at Client Side.

private class Client{


void opensocket() {

 Socket socket = new Socket(Server IP addressServer Port);  // Client socket is created

  InputStream inputStream = socket.getInputStream();  // this will get data from socket.
  
 BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
String x = "";
x = r.readLine();   // So now in x we have our input data, which we can display
}

NOTE : the client code is very simple, since i wanted to show how to achieve functionality code-wise.

In reality, we at client side also run socket creation/communication code as ASYNC task or seperate thread.

Since , reading /writing data from socket can take time, which will make our whole app to hang. So we do that functionality in background.

A bit about ASYNC task :  Classes which implements ASYNC task will run in background so that they don't affect over-all functionality.

Code wise : Classes implement ASYNC task like below

class ClientTask extends AsyncTask {

And then this class needs to implement some fucntions related to Async task like

1) Preexecute :  Function which will be done before Background function.
2) DoinBackground : The code part of this fucntions execute in background.
3) PostExecute : This will get execute after background function is completed.

4) Progress : If you are reading large amounts of data from socket and periodically wants to display that data , you can call this function from inside of DoinBackground. ( Ever notice , in MYNTRA, flipkart,amazon as we scroll items they gets loaded )

More on Async task can be read from internet like : its return type, parameters  etc.




Finally ...I have written the article.  Its so difficult to sit on your ass from long-time. Its time to massage it .

In third article , there will be zip file of  complete code, possible some video also showing communication between Server and Client.  And ...this is far-fetched ...but how to have continuous communication between Server/Client.


Wednesday, March 30, 2016

Sockets : Finally they unraveled themselves : Part 1


Socket programming was something, I was always interested in. But Now when i look back in my college years , I realized that nothing was taught which could have been practical. The teaching situation in india is quite bad.

If internet would have not come, we would still be lagging behind a lot.

Also I am very lazy, until and unless there is no external force, my inertia of rest doesn't allow me to work.


But past is past...behold ..the future is bright.............

Rather than having detailed techincal discussion about them, we will see there overview and then see Android Programming.


1) OSI layer :  If anyone has ever taken any networking course, they know about OSI layer. Below is the diagram



Now , in the above diagram SOCKETS fall between Transport and Session Layer. 
Transport Layer has TCP/UDP.\
 Internet Layer has IP. 

To communicate between any two devices, we need IP address. But what is multiple applications on one device are communicating with other device.  In that case we need PORT, which helps in distinguish traffic flow. 

SOCKET are combination of IP address and PORT, (APPLICATION/Presentation/Session) Layer opens SOCKET with Transport Layer and then all data is read/write from this socket. 


So now we know what is socket and how transfer can be done. Lets see what are API available in Android/Java library to open,close,read,write from a SOCKET. 

Also most of data transfer happening on internet or most of the Android apps we see are based on Server-Client architecture. 

A client will periodic check with Server if some new data is available from him, and will post if any data needs to be posted by Client to Server. 

So if you visualize , Client should know Server IP address, but if Server do not know Client IP address , it will be fine, as onus is on Client and not server. 


So the life - cycle of SOCKET is like below 




1) You create a socket on SERVER using a PORT ID.  ( Note depending on language and platform you are working on , you might also have to BIND the socket to Server IP address)

2) Then SERVER is constantly listening to any NEW CONNECTION coming. 

3) At CLIENT side, we also create socket. NOTE : the use of client side socket is to communicate with SERVER, hence the IP address and PORT no which we provides here is of SERVER.

4) Then CLIENT tries to connect to SERVER. 

5) SEVER once gets CLIENT request, accepts it.

6) Now we have communication link open and data can be transferred between SERVER and CLIENT.

7) Finally we close the connection. 

Now a bit of  Operating System .  If you see SERVER functions design wise, SERVER has to listen to new CLIENT request and also needs to communicate with existing CLIENT, hence we have to need two different THREADS, since both of these functions need to work in parallel. 



Now in Android, we use 

1)  ServerSocket serverSocket  = new ServerSocket(port_no);

    // This is to create Server side socket 

2 and 5) Socket socket_c = serverSocket.accept();

    // This is use to accept client connection, now using socket_c we can communicate with Client, NOTE : we don't use serverSocket to communicate with client, that is only used to listen and accept client connections. Once client connection is accepted, further communication is done using the client socket created at server side for each client.


3 and 4)  socket = new Socket(Server IP address, Server Port);

   // This is used to create socket at client side. This only will also try to connect to server, no other function needs to be called explicitly.



6 ) InputStream inputStream = socket.getInputStream(); 

     // This is used to read data coming to socket, irrespective of socket at server or client side.

    OutputStream outputStream = socket.getOutputStream(); 
    PrintStream printStream = new PrintStream(outputStream);
    printStream.print("data to be send in string format");

    // Below commands are needed to write data into socket.


Viola,  we are almost there. 

So in next post we will see Android App code , as it will also involve thread.