[Tutor] creating a server

nathan tech nathan-tech at hotmail.com
Fri Oct 9 16:22:56 EDT 2020


Hi folks,


going off of the feedback I have created these two files which I have 
attached.

One is the server and the other is a basic client I used to test it.

Notes:

1. In the server I've been a bit lax with the try and except statements 
but I've noted that in the comments as this is just a proof of concept 
for the moment.

2. On the client, if it were a real client, i'd imagine it'd have to 
have a similar set up to the server for sending and receiving, except 
instead of raising on failure, the server would resend the message 
length and start again.


I would be really interested on opinions and thoughts you all may have 
as I continue to learn :)

Thanks in advance

Nathan


On 07/10/2020 22:15, Alan Gauld via Tutor wrote:
> On 07/10/2020 20:33, nathan tech wrote:
>
>> There's a delay due to moderator approval (is that because I am new/)
>> and the question has been answered :)
> If you are new then you will be automatically put on full moderation
> until I get around to removing you.
>
> I've just done that so newer messages should go straight through.
>
> Alan g.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://nam10.safelinks.protection.outlook.com/?url=https%3A%2F%2Fmail.python.org%2Fmailman%2Flistinfo%2Ftutor&data=02%7C01%7C%7C93d6ceec71d2433a0dda08d86b06510b%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C637377022150293957&sdata=iKvFv%2FDOvI39%2FHdbTh8AfXV5FsKwQmhJvVhWS0rG5HU%3D&reserved=0

-------------- next part --------------
# just a simple example sending function
import socket
HOST = "localhost"
PORT = 8000
def send(sock, msg):
 l=len(msg) # number of bites of message
 s.send(b"{"+(str(l).encode("utf8"))+b"}")
 if(sock.recv(2)!=b"ok"):
   raise("Socket error.")
 sock.sendall(msg)
 if(sock.recv(2)!=b"ok"):
   raise("Socket error.")
 return 1
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((HOST, PORT))
send(s, b"Hello!")
print(s.recv(1024))
s.close()
-------------- next part --------------
import socket
import time
class user:
 def __init__(self, sock):
  self.sock=sock
  self.read=b''
  self.msg=b''
  self.expected_length=0
 def rec(self):
  try: # non blocking error avoidance
   data=self.sock.recv(1024)
  except: # will want to put a catch in here for except read error because connection is closed and return something for the main loop to handle
   data=b''
  self.read=self.read+data
  if(self.expected_length != 0):
   if(len(self.read)>=self.expected_length):
    self.msg=self.read[:self.expected_length+1] # +1 because of indexes
    self.read=self.read[self.expected_length+1:]
    self.expected_length=0
    self.sock.send(b"ok")
    self.process()
  if(self.expected_length==0 and len(self.read)>2 and self.read.find(b"{")==0 and self.read.find(b"}")>1):
    before=self.read.find(b"{")
    end=self.read.find(b"}")
    try: # just in case invalid
     self.expected_length=int(self.read[before+1:end])
    except:
     self.sock.send(b"reset")
     self.read=b''
     self.expected_length=0
    self.read=self.read[end+1:]
    self.sock.send(b"ok")
 def process(self):
   if(self.msg==b"Hello!"):
    self.sock.send(b"Hi there, client. It's nice to be working with you!")

users=[]
HOST = 'localhost'
PORT = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(10000) # random high number
s.setblocking(0)
print("Server running.")
while 1: # normally would tie this to a variable of shutdown but for testing purposes keyboard interupt is fine
 try: # catch any and all not ready yet socket errors
   conn, addr = s.accept()
   print("Say hello to ", addr[0], " on port ", addr[1])
   users.append(user(conn))
 except:   # no one wants to join us, sad times
   ok=1 # just a variable so you don't get bugged about syntax
 for x in users:
  x.rec()
 time.sleep(0.01) # so we're not hogging resources. Necessary?


More information about the Tutor mailing list