import thread
import socket
import sys
HOST = socket.gethostname()
print HOST
PORT = 2468
welcome_msg = 0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM )
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print "Socket Created"
try:
s.bind((HOST, PORT))
except socket.error, msg:
print "Bind failed. Error Code : " + str(msg[0]) + " Message " + str(msg[1])
sys.exit()
print "Socket Bind Complete"
"""
So by specifying 10, it means that if 10
connections are already waiting to be processed,
then the 11th connection request shall be rejected.
This will be more clear after checking socket_accept.
"""
s.listen(10)
print "Socket now listening"
def open_welcome():
welcome_txt = open("welcome.txt", "r")
welcome_msg = welcome_txt.read()
print welcome_msg
return welcome_msg
def open_msg():
send_msg = open("send_able.txt", "r")
data = send_msg.read()
send_msg.close()
send_msg = open("send_able.txt", "w+")
send_msg.write("")
send_msg.close()
def old_msg(data):
while True:
oldmsg = open("old_msg.txt", "a+")
try:
oldmsg.write("%s \n" % (data))
except TypeError:
print "SERVER MSG >>> NO MESSAGE SENT"
oldmsg.close()
#Function for handling connections
def clientthread(connection, welcome_msg):
#Sending message to connected client
#This only takes strings (words
connection.send(open_welcome())
#loop so that function does not terminate and the thread does not end
while True:
#Receiving from client
data = connection.recv(1024)
if not data:
break
if data:
connection.sendall(data)
old_msg(data)
print data
connection.close()
def main_server():
while True:
#Wait to accept a connection - blocking call
connection, addr = s.accept()
#display client information (IP address)
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#Start new thread takees 1st argument as a function name to be run, second
#is the tuple of arguments to the function
thread.start_new_thread(clientthread (connection, welcome_msg))
def main():
open_welcome()
open_msg()
main_server()
main()
s.close()