Rabu, 19 Februari 2014

Client-server Socket Programming dalam bahasa Python di Linux

artikel ini membahas cara membuat socket progrmming dalam bahasa python di Linux. cara di bawah ini hanya perlu membuat satu file source code, tetapi tetap menggunakan dua terminal saat menjalankannya. langkah-langkah dalam membuatnya adalah sebagai berikut.
1.  buat soure code server pada text editor. simpan file dengan nama server.py

'''
    Simple socket server using threads
'''

import socket
import sys
from thread import *

HOST = ''   # Symbolic name meaning all available interfaces
PORT = 8889 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

#Bind socket to local host and port
try:
    s.bind((HOST, PORT))
except socket.error as msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()
     
print 'Socket bind complete'

#Start listening on socket
s.listen(10)
print 'Socket now listening'

#Function for handling connections. This will be used to create threads
def clientthread(conn):
    #Sending message to connected client
    conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
     
    #infinite loop so that function do not terminate and thread do not end.
    while True:
         
        #Receiving from client
        data = conn.recv(1024)
        reply = 'OK...' + data
        if not data:
            break
        conn.sendall(reply)
    #came out of loop
    conn.close()

#now keep talking with the client
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])
     
    #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
    start_new_thread(clientthread ,(conn,))

s.close()

3. buka terminal dan masuk ke direktori tempat Anda menyimpan file source code Anda, misal cd Desktop, cd Downloads, dll
3. compile source code dengan mengetikkan python (nama file). kali ini ketikkan dengan perintah python server.py
4. buka terminal baru lalu ketikkan telnet localhost 8889 (localhost disesuaikan dengan yang ada pada source code yang telah dibuat.
7. socket yang dibuat akan memperlihatkan tampilan sebagai berikut. Anda bisa melakukan percakapan pada terminal kedua


Referensi: http://www.binarytides.com/python-socket-server-code-example/

Tidak ada komentar:

Posting Komentar