Wednesday, February 19, 2014

Socket Programming in Phyton

kali ini saya akan memberikan tutorial melakukan socket programming sederhana menggunakan bahasa pemrograman phyton dengan ubuntu.
1. pastikan anda memiliki Source code server.py dan client.py
server.py
#!/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

client.py
#!/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


2. pastikan ubuntu anda telah terinstal compiler phyton. tutorial penginstalannya dapat dilihat disini.
3. lalu buka kedua terminal secara paralel
4. masukkan direktori kedua source code tersebut dengan mengetikkan cd [direktori file]
5. ketikkan phyton server.py &  pada terminal 1. lalu ketikkan phyton client.py pada terminal 2
6. jika sudah berhasil pada terminal akan memberikan hasil seperti gambar dibawah



http://www.tutorialspoint.com/python/python_networking.htm

No comments:

Post a Comment