Python: Demo Server Sederhana

From OnnoWiki
Jump to navigation Jump to search

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


Sebuah Simple Server

Untuk menulis Internet server, To write Internet servers, kita menggunakan fungsi soket yang tersedia di soket modul untuk membuat objek socket. Sebuah objek socket kemudian digunakan untuk memanggil fungsi-fungsi lain untuk setup server socket.

Sekarang memanggil bind (hostname, port) berfungsi untuk menentukan port untuk layanan pada host yang diberikan.

Berikutnya, call metoda untuk menerima objek yang kembali. Metode ini menunggu sampai klien terhubung ke port yang anda tentukan, dan kemudian mengembalikan objek koneksi yang merepresentasikan koneksi ke klien.

# first of all import the socket library
import socket

# next create a socket object
s = socket.socket()
print ("Socket successfully created")

# reserve a port on your computer in our
# case it is 40674 but it can be anything
port = 8888

# Next bind to the port
# we have not typed any ip in the ip field
# instead we have inputted an empty string
# this makes the server listen to requests
# coming from other computers on the network
s.bind((, port))
print ("socket binded to %s" %(port))

# put the socket into listening mode
s.listen(5)
print ("socket is listening")

# a forever loop until we interrupt it or
# an error occurs
while True:

    # Establish connection with client.
    c, addr = s.accept()
    print ('Got connection from', addr )  

    # send a thank you message to the client.
    c.send(b'Thank you for connecting')

    # Close the connection with the client
    c.close()



Sebuah Client Simple

Mari kita menulis sebuah program klien yang sangat sederhana yang akan membuka koneksi ke port 12345 dan host yang ditentukan. Hal ini sangat sederhana untuk membuat klien soket menggunakan fungsi soket modul Python.

socket.connect (hosname, port) membuka sambungan TCP ke nama host pada port. Setelah anda memiliki socket yang terbuka, anda dapat membaca dari socket itu seperti objek IO lainnya. Setelah selesai, ingatlah untuk menutupnya, seperti anda akan menutup file.

Kode berikut adalah klien yang sangat sederhana yang menghubungkan ke host dan port tertentu, membaca data yang tersedia dari soket, dan kemudian exit -

# Import socket module
import socket

# Create a socket object
s = socket.socket()

# Define the port on which you want to connect
port = 8888

# connect to the server on local computer
s.connect(('127.0.0.1', port)) 

# receive data from the server
print(s.recv(1024))

# close the connection
s.close()


Jalankan

Jalankan server.py di background kemudian jalankan client.py untuk melihat hasilnya.

# Following would start a server in background.
$ python server.py & 

Setelah server berjalan, jalankan client sebagai berikut:

$ python client.py

Hasilnya kira-kira

Got connection from ('127.0.0.1', 48437)
Thank you for connecting





Referensi