Socket yang simple dengan python

Coba kirim hello manis melalui soket, Sebelum menulis kode perlu diketahui pada python terdapat class method dan intance nethod. FYI kalau pakai windows perlu install dulu tapi kalau pakai mac os atau linux sudah dari sononya ada.

class method :

Socket Low-level networking interface (per the BSD API)
socket.socket(family, type) Create and return a new socket object
socket.getfqdn(name) Convert a string quad dotted IP address to a fully qualified domain name
socket.gethostbyname(hostname) Resolve a hostname to a string quad dotted IP address
socket.fromfd(fd, family, type) Create a socket object from an existing file descriptor
instance method:
sock.bind( (adrs, port) ) Bind the socket to the address and port
sock.accept() Return a client socket (with peer address information)
sock.listen(backlog) Place the socket into the listening state, able topend backlog outstanding connection requests
sock.connect( (adrs, port) ) Connect the socket to the defined host and port
sock.recv( buflen[, flags] ) Receive data from the socket, up to buflen bytes
sock.recvfrom( buflen[, flags] ) Receive data from the socket, up to buflen bytes, returning also the remote host and port from which the data came
sock.send( data[, flags] ) Send the data through the socket
sock.sendto( data[, flags], addr ) Send the data through the socket
sock.close() Close the socket
sock.getsockopt( lvl, optname ) Get the value for the specified socket option
sock.setsockopt( lvl, optname, val ) Set the value for the specified socket option
Test dulu pakai python interpreter,
>>> import socket
>>> socket.gethostbyname(‘www.ub.ac.id’)
Selanjutnya coba buat tcp stream server simpan dalam file stream.py
import socket
srvsock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
srvsock.bind( (‘ ‘, 2000) )
srvsock.listen( 5 )
while 1:
clisock, (remhost, remport) = srvsock.accept()
str = clisock.recv(100)
clisock.send( str )
clisock.close()

Kemudian buat pengirim.py

import socket
clisock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
clisock.connect( (”, 23000) )
clisock.send(“Hello Manis\n”)
print clisock.recv(100)
clisock.close()

Ngetesnya jalankan didua terminal yang berbeda, satu jalankan python stream.py dan satunya jalankan python pengirim.py. Apakan hello manis sukses dikirim?. Untuk membuktikannya tambahkan print pada stream.py.

……..
clisock.send( str )
print str
clisock.close()

bagaimana hasilnya? Sekian dulu simple socket programing dengan python. :D