69 lines
		
	
	
		
			2.0 KiB
		
	
	
	
		
			PHP
		
	
	
	
			
		
		
	
	
			69 lines
		
	
	
		
			2.0 KiB
		
	
	
	
		
			PHP
		
	
	
	
| <!DOCTYPE html>
 | |
| <html lang="en">
 | |
| <head>
 | |
|     <meta charset="UTF-8">
 | |
|     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 | |
|     <title>Socket Client</title>
 | |
| </head>
 | |
| <body>
 | |
| 
 | |
|     <h1>Socket Client</h1>
 | |
| 
 | |
|     <div id="messages"></div>
 | |
| 
 | |
|     <script>
 | |
|         // Create a WebSocket instance
 | |
|         const socket = new WebSocket('ws://192.168.56.101:2346');
 | |
| 
 | |
|         socket.onopen = function (event) {
 | |
|             console.log("Connected to the server");
 | |
|             console.log({socket, event});
 | |
| 
 | |
|             // Send an initial payload upon connection
 | |
|             const username = 'kai.1';
 | |
|             const payload = {
 | |
|                 username: username
 | |
|             };
 | |
|             socket.send(JSON.stringify(payload));
 | |
|         };
 | |
| 
 | |
|         socket.onmessage = function (event) {
 | |
|             console.log("Received message from the server:", event.data);
 | |
|         };
 | |
| 
 | |
|         // Event handler for when the connection is opened
 | |
|         socket.addEventListener('open', (event) => {
 | |
|             console.log('Connected to the server');
 | |
|         });
 | |
| 
 | |
|         // Event handler for when a message is received from the server
 | |
|         socket.addEventListener('message', (event) => {
 | |
|             // Display the received message on the HTML page
 | |
|             const messagesDiv = document.getElementById('messages');
 | |
|             messagesDiv.innerHTML += '<p>' + event.data + '</p>';
 | |
|         });
 | |
| 
 | |
|         // Event handler for errors
 | |
|         socket.addEventListener('error', (event) => {
 | |
|             console.error('Error occurred:', event);
 | |
|         });
 | |
| 
 | |
|         // Event handler for when the connection is closed
 | |
|         socket.addEventListener('close', (event) => {
 | |
|             console.log('Connection closed:', event);
 | |
|         });
 | |
| 
 | |
|         // Function to send a message to the server
 | |
|         function sendMessage() {
 | |
|             const message = prompt('Enter a message to send:');
 | |
|             if (message) {
 | |
|                 socket.send(message);
 | |
|             }
 | |
|         }
 | |
|     </script>
 | |
| 
 | |
|     <button onclick="sendMessage()">Send Message</button>
 | |
| 
 | |
| </body>
 | |
| </html>
 |