chatServer/serverBlaster.py

77 lines
1.6 KiB
Python

#!/usr/bin/env python3
import sys
oldexcepthook = sys.excepthook
def newexcepthook(type,value,traceback):
oldexcepthook(type,value,traceback)
input("Press ENTER to quit.")
sys.excepthook = newexcepthook
import os
p = os.path.join
pUp = os.path.dirname
s = False
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
s = os.path.realpath(sys.executable)
else:
s = os.path.realpath(__file__)
sp = pUp(s)
# script start
import socket
import threading
class receiverThread(threading.Thread):
def __init__(self,connection):
threading.Thread.__init__(self)
self.connection = connection
def run(self):
while True:
response = getResponse(connection).decode("utf-8")
print("server: " +response)
def sendRequest(connection,data):
connection.sendall(len(data).to_bytes(4,"big") + b"\x00" + data)
def getResponse(connection):
data = b''
data = connection.recv(4)
if not data:
connection.close()
return
nul = connection.recv(1)
if not nul:
connection.close()
return
if nul != b"\x00":
connection.close()
return
requestLength = int.from_bytes(data,"big")
data = connection.recv(requestLength)
return data
def main():
global connection
connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection.connect((sys.argv[1],int(sys.argv[2])))
thread = receiverThread(connection)
thread.start()
while True:
text = input()
data = text.encode("utf-8")
connection.settimeout(15)
sendRequest(connection,data)
connection.settimeout(None)
if text == "exit":
connection.close()
break
if __name__ == '__main__':
main()