|
- #!/usr/bin/env python
-
- import socket, argparse, subprocess
-
- if __name__ == "__main__":
- parser = argparse.ArgumentParser(description='Simple Server')
- parser.add_argument('-p', default=1337, type=int, help='Serverport the server is listen on.')
- parser.add_argument('-a', type=str, required=True, help='IPv4 address of the servers interface for bind.')
- parser.add_argument('--tcp', action='store_true', help='Use TCP.')
- parser.add_argument('--udp', action='store_true', help='Use UDP.')
- args = parser.parse_args()
-
- if args.udp and args.tcp:
- print("Only one protocol is allowed.")
- exit(1)
- elif not args.udp and not args.tcp:
- print("Specify protocol")
- exit(1)
-
- # Port des Servers
- PORT = args.p
- # Lesepuffergröße
- BUFFER_SIZE = 1400
- # Unterstützte Addresstypen (IPv4, IPv6, lokale Addressen)
- address_families = (socket.AF_INET, socket.AF_INET6, socket.AF_UNIX)
- # Unterstützte Sockettypen (TCP, UDP, Raw (ohne Typ))
- socket_types = (socket.SOCK_STREAM, socket.SOCK_DGRAM, socket.SOCK_RAW)
- # Passenden Address- und Sockettyp wählen
- address_family = address_families[0]
- if args.tcp:
- socket_type = socket_types[0]
- else:
- socket_type = socket_types[1]
- # Maximale Anzahl der Verbindungen in der Warteschlange
- backlog = 1
- try:
- # Erstellen eines Socket (TCP und UDP)
- sock = socket.socket(address_family, socket_type)
- sock.bind((args.a, PORT))
- if args.tcp:
- # Lausche am Socket auf eingehende Verbindungen (Nur TCP)
- sock.listen(backlog)
- clientsocket, address = sock.accept()
-
- # mplayer starten
- cmd_mplayer = 'mplayer -fps 25 -cache 512 -'
- mprocess = subprocess.Popen(cmd_mplayer, shell=True, stdin=subprocess.PIPE)
-
- while True:
- # Daten (der Größe BUFFER_SIZE) aus dem Socket holen und ausgeben:
- if args.tcp:
- # TCP:
- data = clientsocket.recv(BUFFER_SIZE)
- else:
- # UDP:
- data, address = sock.recvfrom(BUFFER_SIZE)
- # Die ausgelesenen Daten an mplayer weiterleiten
- mprocess.stdin.write(data)
-
- except KeyboardInterrupt:
- print("Close socket.")
- sock.close()
- print("Exiting through keyboard event (CTRL + C)")
|