11// Create a WebSocket connection 
22const  socket  =  new  WebSocket ( 'ws://localhost:8080' ) ; 
33
4+ // Get references to the message list and input field 
5+ const  messageList  =  document . getElementById ( 'messageList' ) ; 
6+ const  messageInput  =  document . getElementById ( 'messageInput' ) ; 
7+ 48// Event listener for when the connection is opened 
59socket . addEventListener ( 'open' ,  ( event )  =>  { 
610 console . log ( 'Connected to WebSocket server' ) ; 
@@ -9,6 +13,8 @@ socket.addEventListener('open', (event) => {
913// Event listener for messages from the server 
1014socket . addEventListener ( 'message' ,  ( event )  =>  { 
1115 console . log ( `Received from server: ${ event . data }  ) ; 
16+ 17+  appendToList ( event . data ) ; 
1218} ) ; 
1319
1420// Event listener for when the connection is closed 
@@ -26,8 +32,23 @@ socket.addEventListener('error', (event) => {
2632} ) ; 
2733
2834// Send a message to the server 
35+ function  appendToList ( message )  { 
36+  // Create a new list item to display the message 
37+  const  listItem  =  document . createElement ( 'li' ) ; 
38+  listItem . textContent  =  message ; 
39+ 40+  // Append the list item to the message list 
41+  messageList . appendChild ( listItem ) ; 
42+ 43+  // Scroll to the bottom of the message list to show the latest message 
44+  messageList . scrollTop  =  messageList . scrollHeight ; 
45+ } 
2946function  sendMessage ( )  { 
30-  const  message  =  document . getElementById ( 'messageInput' ) . value ; 
31-  console . log ( message ) ; 
47+  const  message  =  messageInput . value ; 
3248 socket . send ( message ) ; 
49+ 50+  // Clear the input field after sending the message 
51+  messageInput . value  =  '' ; 
52+ 53+  appendToList ( message ) ; 
3354} 
0 commit comments