THE CHAT ROOM - PHP Online
Form of PHP Sandbox
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
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.
Result of php executing
Full code of THE CHAT ROOM.php
- <?php# Server
- import socket
- import threading
- class Server:
- def __init__(self, host = '127.0.0.1', port = 55555):
- self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self.server.bind((host, port))
- self.server.listen()
- self.clients = []
- self.nicknames = []
- def broadcast(self, message):
- for client in self.clients:
- client.send(message)
- def handle(self, client):
- while True:
- try:
- message = client.recv(1024)
- self.broadcast(message)
- except:
- index = self.clients.index(client)
- self.clients.remove(client)
- client.close()
- nickname = self.nicknames[index]
- self.nicknames.remove(nickname)
- self.broadcast(f'{nickname} left the chat!'.encode('ascii'))
- break
- def receive(self):
- while True:
- client, address = self.server.accept()
- print(f"Connected with {str(address)}")
- client.send('NICK'.encode('ascii'))
- nickname = client.recv(1024).decode('ascii')
- self.nicknames.append(nickname)
- self.clients.append(client)
- print(f"Nickname of the client is {nickname}!")
- self.broadcast(f"{nickname} joined the chat!".encode('ascii'))
- client.send('Connected to the server!'.encode('ascii'))
- thread = threading.Thread(target=self.handle, args=(client,))
- thread.start()
- server = Server()
- server.receive()