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
- # some global variables for configuration
- username = "123456"
- password = "random@rhrk.uni-kl.de"
- 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))
- print "Note: Press CTRL+C to exit client.\n"
- def primfaktoren(n):
- faktoren = []
- z = n
- while z > 1:
- # bestimme den kleinsten Primfaktor p von z
- i = 2
- gefunden = False
- while i*i <= n and not gefunden:
- if z % i == 0:
- gefunden = True
- p = i
- else:
- i = i + 1
- if not gefunden:
- p = z
- faktoren = faktoren + [p]
- z = z // p
- return faktoren
- # line by line
- for m in s.makefile():
- msg = re.match("^([0-9]+)(#(.+))?\r\n$", 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
- s.send("1#%s\r\n" % username)
- print "Client: My name is '%s'" % username
- # server requests password
- elif cmd == "2":
- print "Server: %s" % args
- s.send("2#%s\r\n" % password)
- print "Client: Password is '%s'" % password
- # logged in successfully
- elif cmd == "3":
- print "Server: %s" % args
- s.send("6\r\n") # 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)
- s.send("9\r\n")
- 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)
- s.send("10\r\n")
- elif cmd == "10":
- print "Server: " + args
- send = "11"
- for p in primfaktoren(int(args)):
- send += "#" + str(p)
- send += "\r\n"
- s.send(send)
- print "Client: " + send
- elif cmd == "11":
- print "Server: " + args
- # 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