Rabu, 19 Februari 2014

Socket Client-Server in Python

Socket dapat digunakan dalam beberapa bahasa seperi Java, C++ dan lainnya. Berikut pengaplikasian socket dengan menggunakan program bahasa Python.


Berikut langkah - langkah untuk membuat dan menjalankan socket dalam bahasa Python pada linux :

1. Buatlah sebuah file dengan nama server.py
2. Setelah itu compile file server.py 
3. Buatlah sebuah file dengan nama client.py
4. Setelah itu compile file client.py
5. Setelah itu jalankan kedua program yang telah di compile pada terminal yang berbeda. 

Berikut Source code untuk socket 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.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection

 berikut source code untuk socket 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.

s.connect((host, port))
print s.recv(1024)
s.close                     # Close the socket when done
 
 Berikut hasil kedua source code diatas setelah dijalankan :



Reference :
1. http://www.tutorialspoint.com/java/java_networking.htm

Tidak ada komentar:

Posting Komentar