Monday, August 25, 2014

python server socket example first app

# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.

__author__="boroo"
__date__ ="$Aug 12, 2014 11:05:45 PM$"

'''
    Simple socket server using threads
'''

import socket
import sys

print bool( (1,) )
#sys.exit()

HOST = ''   # Symbolic name, meaning all available interfaces
PORT = 8888 # 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'

accepted = bool(0)
#now keep talking with the client
while accepted == 0:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])
    accepted = 1
s.close()

if __name__ == "__main__":
    print ("end.")


usage

telnet o localhost 8888

No comments: