THE CHAT ROOM - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of THE CHAT ROOM.php

  1. <?php# Server
  2. import socket
  3. import threading
  4.  
  5. class Server:
  6.     def __init__(self, host = '127.0.0.1', port = 55555):
  7.         self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  8.         self.server.bind((host, port))
  9.         self.server.listen()
  10.  
  11.         self.clients = []
  12.         self.nicknames = []
  13.  
  14.     def broadcast(self, message):
  15.         for client in self.clients:
  16.             client.send(message)
  17.  
  18.     def handle(self, client):
  19.         while True:
  20.             try:
  21.                 message = client.recv(1024)
  22.                 self.broadcast(message)
  23.             except:
  24.                 index = self.clients.index(client)
  25.                 self.clients.remove(client)
  26.                 client.close()
  27.                 nickname = self.nicknames[index]
  28.                 self.nicknames.remove(nickname)
  29.                 self.broadcast(f'{nickname} left the chat!'.encode('ascii'))
  30.                 break
  31.  
  32.     def receive(self):
  33.         while True:
  34.             client, address = self.server.accept()
  35.             print(f"Connected with {str(address)}")
  36.  
  37.             client.send('NICK'.encode('ascii'))
  38.             nickname = client.recv(1024).decode('ascii')
  39.             self.nicknames.append(nickname)
  40.             self.clients.append(client)
  41.  
  42.             print(f"Nickname of the client is {nickname}!")
  43.             self.broadcast(f"{nickname} joined the chat!".encode('ascii'))
  44.             client.send('Connected to the server!'.encode('ascii'))
  45.  
  46.             thread = threading.Thread(target=self.handle, args=(client,))
  47.             thread.start()
  48.  
  49. server = Server()
  50. server.receive()
  51.  
  52.  
File Description
  • THE CHAT ROOM
  • PHP Code
  • 05 Dec-2023
  • 1.55 Kb
You can Share it: