Advertisement
Bad_Programist

Untitled

Apr 17th, 2019
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.01 KB | None | 0 0
  1. import socket
  2. from _thread import *
  3. from Objects import ServerCont, Player
  4. import pygame
  5. import sys
  6. import pickle
  7.  
  8. host = '192.168.1.65'
  9. port = 5000
  10. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  11. s.bind((host, port))
  12. s.listen(2)
  13. print('Server started')
  14. connected = set()
  15. games = {}
  16. idCount = 0
  17. connections = {}
  18.  
  19.  
  20. def threaded_client(c, p, gameId):
  21.     global idCount, games
  22.     c.send(str.encode(str(p)))
  23.     reply = ''
  24.     while True:
  25.         try:
  26.             data = pickle.loads(c.recv(4096 * 2))
  27.             if gameId in games:
  28.                 cont = games[gameId]
  29.                 if not data:
  30.                     break
  31.                 else:
  32.                     if data != 'get' and not isinstance(data, Player):
  33.                         cont.changedirCl(p, data)
  34.                     if p == 1 and cont.run and data == 'get':
  35.                         cont.move_snakes_mul(20)
  36.                     if isinstance(data, Player):
  37.                         if p == 0:
  38.                             cont.p0 = data
  39.                         elif p == 1:
  40.                             cont.p1 = data
  41.                     else:
  42.                         reply = cont
  43.                         c.sendall(pickle.dumps(reply))
  44.                     if not cont.run:
  45.                         break
  46.             else:
  47.                 break
  48.         except Exception as e:
  49.             print(e)
  50.             print(type(e))
  51.             break
  52.  
  53.     print('Lost connection')
  54.     print('Closing game', gameId)
  55.     idCount -= 1
  56.     try:
  57.         del games[gameId]
  58.     except Exception as e:
  59.         print(e)
  60.         print(type(e))
  61.     c.close()
  62.  
  63. while True:
  64.     c, addr = s.accept()
  65.     print(f'Connected to {addr} with Id {idCount}')
  66.  
  67.     idCount += 1
  68.     p = 0
  69.     gameId = (idCount - 1) // 2
  70.     if idCount % 2 == 1:
  71.         games[gameId] = ServerCont(gameId)
  72.         print('Creating a new Game...')
  73.     else:
  74.         p = 1
  75.         games[gameId].ready = True
  76.  
  77.     start_new_thread(threaded_client, (c, p, gameId))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement