This script provides a simple to use base server class and a Socket object that abstracts away the needed work to transport and recieve messages over TCP.
NOTE: The method used to reconstruct fragments does not work with protocols such as HTTP. This is designed to be used with simple self designed protocols.
pip install gruv_socks
Simple examples to show you how the library can be used.
from gruv_socks.gruv_socks import server_test
print(server_test())
b"If you see this message, that means gruv_socks is working!"
This script will create a server that listens for data from clients, sends it back, then closes the connection. It will continue to run until stopped with Ctrl+C
due to the blocking=True
parameter in line 14. The deconstructor of the Socket object ensures it is properly closed, so you do not need to explicitly call it unless needed.
from gruv_socks.gruv_socks import ServerBase, SOCK_ERROR, SOCK_TIMEOUT
def callback(addr, sock):
status, data = sock.read() # receive read status, and received data
# exit if read failed
if status is False:
if data == SOCK_ERROR:
print("client error")
elif data == SOCK_TIMEOUT:
print("client timeout")
return
sock.write(data) # send data back to client
print(f"{addr[0]} said: {data.decode()}")
def main():
server = ServerBase()
server.start(callback, 5551, blocking=True)
if __name__ == "__main__":
main()
This script will connect to the server running from the above script, send the text "Hello world!" disconnect, and then exit.
from gruv_socks.gruv_socks import Socket
def main():
sock = Socket()
sock.connect("localhost", 5551)
sock.write("Hello world!")
print(sock.read()[1])
sock.disconnect()
if __name__ == "__main__":
main()
A breakdown of the provided functions, objects, and variables.
Use to determine if a socket encountered an error.
Use to determine if a socket encountered a time out.
Simple callback function to create an echo server with the ServerBase object.
Direct call function to test the BaseServer and Socket objects locally on the machine running it to ensure the library is working.
Timeout (in seconds) to use for socket operations.
Decides if stack trace information is printed to console or not.
Holds the underlying socket object that communication is preformed with.
sock: Existing socket to use if supplied.
timeout: Time to wait (in seconds) for certain socket operations before stopping. I.e. connecting, reading data.
debug: If set to true, the stack trace will be printed to console upon errors for debugging.
def __str__(self) -> str:
return f"gruv_socks.Socket(timeout={self.timeout}, debug={self.debug})"
Shorthand for Socket.write()
def __add__(self, x: bytes) -> bool:
return self.write(x)
Usage
from gruv_socks.gruv_socks import Socket
sock = Socket()
sock.connect("localhost", 5551)
sock + b"Hello world!"
Attempts to establish a connection to a given host. Returns bool dictating status.
host: Hostname/Address of host to connect to.
port: Port on the given host to connect to.
Attempts to read data from the socket object.
Returns a tuple containing a boolean dictating success status, and then the received data in byte string. If the status is False, then either gruv_socks.SOCK_ERROR, or gruv_socks.SOCK_TIMEOUT will be returned as the data.
timeout_override: If not 0, then overrides the set timeout for this singular read call.
Attempts to write data to socket object, sending it to the connected host. Returns boolean dictating status.
data: Data to send to connected host.
Properly disconnects the socket object by shutting down READ/WRITE channels, and then closing the socket.
Socket destructor, ensures the socket object properly closes before being destroyed.
Initializes the ServerBase object.
debug: Decides if stack trace information is printed to console or not.
Listens for incoming connections and hands them off to the callback function supplied.
Makes the server listen with the given configuration.
The callback function is supplied 2 arguments. The first is a tuple of the remote IP, and the remote port. The second argument is the Socket object of the remote connection.
callback: Callback function to trigger upon new connections. callback( (host: str, port: int), Socket )
port: Port to listen on.
address: Address to listen on.
blocking: Boolean dictating wether or not this function should block, or spawn a thread to listen.
Stops the server by shutting down the listening socket and triggering the background thread to stop.
Ensures the listening socket is properly closed, and the listening thread exits gracefully.