Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python2
- # sockets are the interface to network
- # connections for programmers
- import socket
- # the regular expressions are needed
- # to parse the protocol; see FGDP or
- # https://docs.python.org/2/howto/regex.html
- import re
- # https://docs.python.org/2/library/threading.html#threading.Timer
- from threading import Timer
- # some global variables for configuration
- username = "123456"
- password = "name@provider.com"
- chathost = "131.246.19.102"
- chatport = 1337
- # setup connection to the chat server
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- s.setblocking(True)
- s.connect((chathost, chatport))
- last = None
- def resend():
- global s, last
- s.send(last+"\r\n")
- def send(msg):
- global s, last
- s.send(msg+"\r\n")
- last = msg
- # line by line
- for m in s.makefile():
- msg = re.match("^([0-9]+)(#(.+))?\r$", m)
- if msg is None:
- print "Warning: server sent message with unknown format:\n\t'%s'" % m
- continue # skip this message
- cmd, _, args = msg.groups()
- # server message
- if cmd == "0":
- print "Server: %s" % args
- # servers requests username
- elif cmd == "1":
- print "Server: %s" % args
- send("1#%s" % username)
- print "Client: My name is '%s'" % username
- # server requests password
- elif cmd == "2":
- print "Server: %s" % args
- send("2#%s" % password)
- print "Client: Password is '%s'" % password
- # logged in successfully
- elif cmd == "3":
- print "Server: %s" % args
- send("6") # request list of online users
- print "Client: Who's online?"
- # another user logged in
- elif cmd == "4":
- print "Server: User '%s' joined the chat." % args
- # another user logged out
- elif cmd == "5":
- print "Server: User '%s' left the chat." % args
- # list of online users
- elif cmd == "6":
- usrs = args.split("#")
- print "Server: Online users are "+", ".join(usrs)
- send("9")
- print "Client: Which exercises did I pass so far?"
- # message from another user
- elif cmd == "7":
- user, text = re.match("^(.+?)#(.+)$", args).groups()
- print "%s: %s" % (user, text)
- # list of all finished assignments
- elif cmd == "9":
- if (args == None):
- print "Server: You've not completed any task yet? Come ooooonn...."
- continue
- exs = args.split("#")
- print "Server: You've completed exercises "+", ".join(exs)
- send("12") # start the game
- # received challenge response
- elif cmd == "11":
- print "Server: %s" % args
- # count up
- elif cmd == "12":
- t.cancel()
- print "Server: The counter is at %s." % args
- send("12#"+args)
- t = Timer(30.0, resend)
- t.start()
- # unknown message type
- else:
- print "Warning: Received unimplemented message of type %s." % cmd
- print "Exiting..."
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement