Showing posts with label Network programming. Show all posts
Showing posts with label Network programming. Show all posts

Saturday, September 15, 2012

Communicating with two language

Previously we implemented the python server. Now it's time to bring up our client part.
Android Client will send downloading url to Python server and Python Server will download the passed URL.

You can see the code repository (Python Server) :
 https://github.com/subh007/Python/blob/master/server_PC.py

You can see the code repository (Android Client) :
 https://github.com/subh007/Android_Client/tree/master/AndroClient

screen shot of client:

Android Client
Python Server












:) B-)

Tuesday, September 11, 2012

Server extended to download file.

In previous post i created a server-client pair using the python.
It is enhanced in such a way that client will pass a download link
to server and server will download the link.

import sys
import socket
sys.path.append('/home/subhash/subh/python/requests')
import requests
s=socket.socket()
hostname=socket.gethostname()
port=9595
s.bind((hostname,port))
s.listen(5)
while True:
    print 'server started'
    conn,addr=s.accept()
    data=conn.recv(1024)
    print(data)
    r=requests.get(data)
    with open('downloded.pdf',"wb") as code:
     code.write(r.content);
     print 'page downloaded'
    conn.close()
s.close()


you can see the code in git. :) B-)

How to kill the process at port XXXX

Sometime we require to kill the process at port.

For example.

s=socket.socket()
hostname=socket.gethostname()
port=9494
bind((hostname,port))

...
..
(pressed ctrl+d)

this will cause the process to still run on port 9494. So whenever we try to
bind the same port to another proce then it will give error:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 98] Address already in use

So, we need to kill the process at that port and it is done by:

$kill -9 `fuser -n tcp 9494`

:) B-)

Monday, September 10, 2012

Download files using request

This is simple example to use request for downloading the files.

import urllib

import sys
#adding the requests http://docs.python-requests.org/en/latest/index.html
import requests
print sys.argv[1]
# url to download
r=requests.get(sys.argv[1])
with open(sys.argv[2],"wb") as code:
#argv[2] is target file name
 code.write(r.content)
 

here, argv[1] is the link for the download file ( ex.- https://google.com) 
and argv[2] is the target file (ex. google.html).

run it by
#python script.py http://google.com google.html

happy coading :) B-)

Reference:
download code from git
http://docs.python-requests.org/en/latest/

Sunday, September 9, 2012

Simple Server - Client program in python

I got a good example for server client in python.

Server :

#!/usr/bin/python           # This is server.py file
 import socket               # Import socket module
s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
 
print 'Server started!'
print 'Waiting for clients...'
 
s.bind((host, port))        # Bind to the port
s.listen(5)                 # Now wait for client connection.
c, addr = s.accept()     # Establish connection with client.
print 'Got connection from', addr
while True:
   msg = c.recv(1024)
   print addr, ' >> ', msg
   msg = raw_input('SERVER >> ')
   c.send(msg);
   #c.close()                # Close the connection




Client :


#!/usr/bin/python           # This is client.py file
 
import socket               # Import socket module
s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
 
print 'Connecting to ', host, port
s.connect((host, port))
 
while True:
    msg = raw_input('CLIENT >> ')
    s.send(msg)
    msg = s.recv(1024)
    print 'SERVER >> ', msg
#s.close                     # Close the socket when done






Reference :
http://www.dscripts.net/2010/06/18/how-to-create-a-client-server-socket-connection-in-python/

 

Sunday, August 21, 2011

A simple TCP echo server and client

This is simple example of tcp server and client. Here client write something on server socket and server write same message back to client.

Few observation:
- What happen if client tries to write 40 byte of date on server socket and reads   40 byte while server writes 20 and reads 20.
- fork process share its parent file descriptor. 
- In the forked server socket try to print on terminal some message without use of '\n' it will not print
 e.g.
 void str_echo(int sockfd)
    {
      char buff[20];
      ssize_t n;
      while(1)
          {
           if((n=read(sockfd,buff,20))>=0)
              write(sockfd,buff,20);
           else
              write(sockfd,"blank",20);
           //else
             printf("%s\n",buff);        // if i replace it with printf("%s",buff) then it wont work
             // write(sockfd,buff,20);
              //return;
           //else
             // writen(sockfd,buff,n);
           }
     }
echo server:
#include<stdio.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<string.h>
#include"str_echo.c"


    

int main()
  {
   int sockfd,connfd,childpid,clilen;
   struct sockaddr_in cliaddr,servaddr;

   sockfd=socket(AF_INET,SOCK_STREAM,0);
 
   bzero(&servaddr,sizeof(servaddr));
   servaddr.sin_family=AF_INET;
   servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
   servaddr.sin_port=htons(6060);
   bind(sockfd,(struct sockaddr*) &servaddr,sizeof(servaddr));
   
   listen(sockfd,5);

   while(1)
     {
      clilen=sizeof(cliaddr);
      connfd=accept(sockfd,(struct sockaddr*)&cliaddr,&clilen);
      printf("connection accepted\n");
       if((childpid=fork())==0)
          {
            close(sockfd);
            printf("child process\n");
            str_echo(connfd);
           // str_echo(connfd);
            exit(0);
          }
     printf("connection established\n");
     close(connfd);
     }
}

echo client:
#include<stdio.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<string.h>
#include"str_cli.c"

int main()
   {
   int sockfd;
   char buff[20];
    ssize_t n;
   struct sockaddr_in servaddr;
    printf("before socket");
   sockfd=socket(AF_INET,SOCK_STREAM,0);
   printf("socket created");
   bzero(&servaddr,sizeof(servaddr));
   servaddr.sin_family=AF_INET;
   inet_pton(AF_INET,"127.0.0.1",&servaddr.sin_addr);
   servaddr.sin_port=htons(6060);
   //bind(sockfd,(struct sockaddr*)&cliaddr,sizeof(cliaddr));
   printf("before connection");
   if(connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr))==0)
      {
         printf("inside loop");
         str_cli(sockfd); 
         /*write(sockfd,"sdfhsdkf",20);
          printf("request send");
         n=read(sockfd,buff,20);
         printf("%s",buff);*/
       }
   printf("after connection");
   close(sockfd);
   }