Below are a real-time chat server and its front-end. I'd like to add a new feature that allows the user to specify a target language to translate his text. Append the translated text to the original one. Use "https://translate.googleapis.com/translate_a/single". Set the source language to "auto". The target language defaults to "en". An input field is used to specify target languages, such as "en", "ja", "zh-TW ", ...etc. Note that chat.js and epic.js are not included here.(server.js) require('dotenv').config() const express = require('express') const app = express()const path = require('path') const html = path.join(__dirname, '/html'); app.use(express.static(html))const port = process.argv[2] || 8090; const http = require("http").Server(app);const maxHttpBufferSizeInMb = parseInt(process.env.MAX_HTTP_BUFFER_SIZE_MB || '1'); const io = require("socket.io")(http, { maxHttpBufferSize: maxHttpBufferSizeInMb * 1024 * 1024, }); let messageCache = []; // default cache size to zero. override in environment let cache_size = process.env.CACHE_SIZE ?? 0http.listen(port, function(){ console.log("Starting server on port %s", port); });const users = []; let msg_id = 1; io.sockets.on("connection", function(socket){ console.log("New connection!");
var nick = null;

socket.on("login", function(data){
    // Security checks
    data.nick = data.nick.trim();

    // If is empty
    if(data.nick == ""){
        socket.emit("force-login", "Nick can't be empty.");
        nick = null;
        return;
    }

    // If is already in
    if(users.indexOf(data.nick) != -1){
        socket.emit("force-login", "This nick is already in chat.");
        nick = null;
        return;
    }

    // Save nick
    nick = data.nick;
    users.push(data.nick);

    console.log("User %s joined.", nick.replace(/(<([^>]+)>)/ig, ""));
    socket.join("main");

    // Tell everyone, that user joined
    io.to("main").emit("ue", {
        "nick": nick
    });

    // Tell this user who is already in
    socket.emit("start", {
        "users": users
    });

    // Send the message cache to the new user
    console.log(`going to send cache to ${nick}`)
    socket.emit("previous-msg", {
        "msgs": messageCache
    });
});

socket.on("send-msg", function(data){
    // If is logged in
    if(nick == null){
        socket.emit("force-login", "You need to be logged in to send message.");
        return;
    }

    const msg = {
        "f": nick,
        "m": data.m,
        "id": "msg_" + (msg_id++)
    }

    messageCache.push(msg);
    if(messageCache.length > cache_size){
        messageCache.shift(); // Remove the oldest message
    }

    // Send everyone message
    io.to("main").emit("new-msg", msg);

    console.log("User %s sent message.", nick.replace(/(<([^>]+)>)/ig, ""));
});

socket.on("typing", function(typing){
    // Only logged in users
    if(nick != null){
        socket.broadcast.to("main").emit("typing", {
            status: typing,
            nick: nick
        });

        console.log("%s %s typing.", nick.replace(/(<([^>]+)>)/ig, ""), typing ? "is" : "is not");
    }
});

socket.on("disconnect", function(){
    console.log("Got disconnect!");

    if(nick != null){
        // Remove user from users
        users.splice(users.indexOf(nick), 1);

        // Tell everyone user left
        io.to("main").emit("ul", {
            "nick": nick
        });

        console.log("User %s left.", nick.replace(/(<([^>]+)>)/ig, ""));
        socket.leave("main");
        nick = null;
    }
});
});(index.html) <!DOCTYPE html><html> <head> <meta charset="utf-8"> <title>Chat</title>
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

<link href="static/styles/style.css" rel="stylesheet" type="text/css">
<link href="static/styles/dark.css" rel="stylesheet" type="text/css">
</head> <body> <div class="chat"> <div id="chat-box" class="chat-box"> <div id="offline"><span class="big">Server is offline.</span><br />Sorry for that.</div> <ul id="msgs" class="msgs"></ul> <ul id="typing" class="msgs"></ul> </div> <div class="chat-form"> <ul id="emic" style="display:none;"></ul> <button id="emic_btn"> <img src="static/emic/white-smiling-face.png" width="20px" height="20px" title="White Smiling Face"> </button> <textarea id="form_input" class="form-control" data-user-id="2" placeholder="Type something ..." rows="1"></textarea> <button id="send">Send</button> <ul id="users"></ul> </div> </div>
<script type="text/javascript" src="socket.io/socket.io.js"></script>
<script type="text/javascript" src="static/scripts/emic.js"></script>
<script type="text/javascript" src="static/scripts/chat.js"></script>
<script type="text/javascript">
    // optionally set own server where the client connects to
    const socket = io(location.protocol + '//' + location.host, { path: location.pathname.replace(/\/$/, '') + '/socket.io/' })

    Emic.init();
    Chat.init(socket);
</script>
</body> </html>
So I have this chat application, and I need to add a feature where users can specify a target language to translate their messages. The translated text should be appended to the original message. I need to use the Google Translate API for this, specifically the endpoint "https://translate.googleapis.com/translate_a/single". The source language should be set to "auto", and the target language defaults to "en" if not specified. There will be an input field for the user to specify the target language, like "en", "ja", "zh-TW", etc.
First, I need to understand how the current chat system works. From the server.js file, it looks like it's using Express and Socket.IO to handle real-time communication. When a user connects, they log in with a nickname, and then they can send messages which are broadcasted to all other users in the "main" room. There's also a message cache that keeps track of recent messages, and new users receive this cache when they join.
Now, for the translation feature, I need to modify both the client-side and possibly the server-side code. Since the translation is based on user input, it makes sense to handle the translation on the client-side before sending the message to the server. However, considering that the translation API might require server-side handling for security reasons (like keeping API keys secret), I should think about where to place the translation logic.
Wait, actually, in this case, since it's a public API and doesn't require an API key (I think), it might be okay to call it from the client-side. But generally, it's better to handle such things on the server to avoid exposing any potential sensitive information and to have more control over the requests.
Let me check the Google Translate API documentation quickly. Hmm, actually, upon second thought, the "https://translate.googleapis.com/translate_a/single" endpoint is a free API that doesn't require authentication for basic usage, but it's unofficial and might have limitations or change without notice. For a production application, it's better to use the official Google Cloud Translation API, which requires an API key. However, since the problem specifies to use this particular endpoint, I'll proceed with that, but keep in mind that in a real-world scenario, I should use the official API with proper authentication.
Given that, I can make the translation request from the client-side. But to make it more secure and manageable, perhaps I should handle the translation on the server-side. That way, if I need to switch to the official API later, it's easier to manage the API key on the server.
Wait, but the problem says "the user to specify a target language to translate his text", which implies that each user can choose their own target language for their messages. Wait, actually, re-reading the problem: "allows the user to specify a target language to translate his text. Append the translated text to the original one."
So, when a user sends a message, they can specify a target language, and the message sent to the server should include both the original text and the translated text appended to it.
Wait, but the translation needs to happen before sending the message to the server, right? Because the server just broadcasts whatever message it receives.
Alternatively, the server could handle the translation, but that might not make sense because each user might want to translate to different languages, but actually, in this setup, it seems that the translation is per message, based on the sender's choice.
Wait, let's think carefully. The user specifies a target language, and then when they send a message, the message should be translated to that language and appended to the original message. So, for example, if the user sets the target language to "ja", and types "Hello", the message sent should be "Hello[translated to ja]".
Then, when the server broadcasts this message, all users will see "Hello[translated to ja]".
Wait, but that might not be ideal, because other users might not understand Japanese. Alternatively, perhaps the translation is meant to be done on the receiver's side, so each receiver can choose their preferred language to see the messages in.
But the problem says "translate his text", meaning the sender's text, and "append the translated text to the original one", so it seems like the sender specifies the language, and the message includes both original and translated text.
That seems a bit unusual, but okay, I'll follow the specification.
So, in that case, the client needs to, before sending the message, translate the text to the specified language and append it to the original message, then send this combined message to the server.
To do this, I need to:
  1. Add an input field in the HTML for the user to specify the target language.
  2. In the client-side JavaScript (probably chat.js), when the user sends a message, first make a request to the translation API with the message and the target language, get the translated text, append it to the original message, and then send this combined message to the server via Socket.IO.
  3. The server doesn't need to change much; it will just broadcast whatever message it receives.
Wait, but actually, since the translation is done on the client-side, and the server just broadcasts the message, that should work.
However, there are a few considerations:
  • The translation API call is asynchronous, so I need to handle the promise or callback properly before sending the message.
  • I need to handle errors, like if the translation fails, perhaps just send the original message.
  • Also, since it's a real-time chat, I need to make sure that the translation doesn't introduce too much delay.
But for now, I'll assume that the API is fast enough.
First, let's think about how to add the input field for the target language.
In the index.html, there's a chat-form div with the message input and send button. I can add another input field there for the target language.
For example:
html

<div class="chat-form">

    <input type="text" id="target-language" placeholder="Target language (e.g., en, ja, zh-TW)" value="en">

    <textarea id="form_input" class="form-control" data-user-id="2" placeholder="Type something ..." rows="1"></textarea>

    <button id="send">Send</button>

    <!-- other elements -->

</div>
So, I added an input field with id "target-language" and default value "en".
Now, in the client-side JavaScript, I need to get the value of this input when sending the message.
Assuming that chat.js handles the sending of messages, I need to modify the part where it sends the message.
Probably, there's a function that gets called when the send button is clicked or when enter is pressed in the textarea.
In that function, instead of directly sending the message, I need to first get the target language, make the translation API call, get the translated text, append it to the original message, and then send it.
First, I need to know how to make the API call to Google Translate.
The endpoint is "https://translate.googleapis.com/translate_a/single", and it's a GET request with parameters.
From what I recall, the parameters are:
  • client: gtxx
  • sl: source language (auto in this case)
  • tl: target language
  • dt: t (for translation)
  • q: the text to translate
So, for example, to translate "Hello" to Japanese, it would be:
And the response is a JSON array, where the first element is another array containing the translated text.
For example, it might return:
[[["こんにちは","Hello",null,null,1]],null,"en"]
So, I need to parse this response to get the translated text.
In JavaScript, I can use fetch to make the API call.
So, in the send message function, I can do something like:
async function sendMessage() {
const message = document.getElementById('form_input').value;

const targetLang = document.getElementById('target-language').value || 'en';

if (message.trim() === '') return;

try {

    const response = await fetch(`https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${targetLang}&dt=t&q=${encodeURIComponent(message)}`);

    const data = await response.json();

    const translatedText = data[0][0][0];

    const fullMessage = `${message} [${translatedText}]`;

    // Now send fullMessage to the server

    socket.emit('send-msg', { m: fullMessage });

} catch (error) {

    console.error('Translation error:', error);

    // If translation fails, just send the original message

    socket.emit('send-msg', { m: message });

}

// Clear the input field

document.getElementById('form_input').value = '';
}
Wait, this seems straightforward.
But I need to make sure that this is integrated properly with the existing code.
Since chat.js is not provided, I have to assume how it's structured.
Probably, there's an event listener on the send button or on the textarea for keypress.
For example, something like:
document.getElementById('send').addEventListener('click', function() {
const message = document.getElementById('form_input').value;

socket.emit('send-msg', { m: message });

document.getElementById('form_input').value = '';
});
So, I need to modify this to include the translation step.
Also, since fetch is asynchronous, I should make the function async or use .then() to handle the promise.
In my example above, I used async/await for simplicity.
But I need to ensure that the chat.js supports async functions or handle promises properly.
Alternatively, I can use .then() to chain the promises.
For example:
document.getElementById('send').addEventListener('click', function() {
const message = document.getElementById('form_input').value;

const targetLang = document.getElementById('target-language').value || 'en';

if (message.trim() === '') return;

fetch(`https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${targetLang}&dt=t&q=${encodeURIComponent(message)}`)

    .then(response => response.json())

    .then(data => {

        const translatedText = data[0][0][0];

        const fullMessage = `${message} [${translatedText}]`;

        socket.emit('send-msg', { m: fullMessage });

    })

    .catch(error => {

        console.error('Translation error:', error);

        socket.emit('send-msg', { m: message });

    });

document.getElementById('form_input').value = '';
});
This way, even if the translation fails, the original message is still sent.
Also, I should consider adding some indication to the user that the message is being translated, but for simplicity, I'll omit that for now.
Additionally, I might want to cache the target language selection, perhaps in local storage, so that the user doesn't have to enter it every time, but again, for this task, I'll keep it simple.
Wait, actually, since the input field has a default value of "en", and it's in the chat form, it will persist as long as the page isn't refreshed. If the user changes it, it will stay changed until they change it again or refresh the page.
That might be acceptable.
Alternatively, I could add a feature to save the preferred language in local storage, but that's beyond the scope.
Another thing to consider is that the translation API might have rate limits or restrictions, but since this is for a chat application, and assuming it's not heavily used, it should be fine.
Also, I need to make sure that the message doesn't exceed any size limits when appending the translated text, but since the server has a maxHttpBufferSize, and the messages are typically short, it should be okay.
Wait, actually, in the server.js, there's a maxHttpBufferSize set to 1MB by default, which is more than enough for text messages.
Moreover, in the send-msg event, the server just broadcasts the message as is, so as long as the client sends a string, it should work.
One more thing: in the message cache, the server stores the messages, and when a new user joins, it sends the previous messages. Since the messages already include the translated text, the new user will see the original and translated text as well.
That seems consistent.
Wait, but actually, in the problem statement, it says "Append the translated text to the original one", so when displaying the message, it will show both.
In the current chat.js, probably, when receiving a new message, it appends it to the #msgs list.
So, the message will be displayed as "original [translated]", which is what we want.
I think that's fine.
Let me think if there's any other aspect I need to consider.
Oh, perhaps I should add some formatting to distinguish the original and translated text, like putting the translated text in italics or something, but since the problem doesn't specify, I'll just append it in brackets as in the example.
Also, I need to make sure that the translation API call is properly encoded, especially since the message might contain special characters.
In the fetch call, I'm using encodeURIComponent(message), which should handle that.
Additionally, I should consider that the translation might not always succeed, for example, if the target language is invalid, or if the API is down, but in the catch block, I'm sending the original message, so it should be okay.
Another point: since the translation is done on the client-side, each user's browser will make the API call, which might lead to multiple calls if many users are sending messages, but again, for this simple application, it should be acceptable.
Alternatively, to optimize, I could have the server handle the translation, but that would require sending the target language along with the message, and having the server make the API call, which might be overkill.
Moreover, since each user might want to translate to different languages, but wait, in this setup, the translation is per message, based on the sender's choice, and the translated text is appended and sent to everyone.
So, actually, if the server handles the translation, it would be the same, because the translation is done once per message, and then broadcasted.
But in terms of implementation, doing it on the client-side is simpler, as I don't need to modify the server code much.
Wait, actually, in this case, since the translation is specific to the sender's choice, and the result is appended to the message, doing it on the client-side makes sense.
Alternatively, if I were to do it on the server-side, I would need to send the target language along with the message, and have the server make the translation API call, then append the translated text and broadcast it.
That could also work, and it might be better in terms of centralizing the API calls, but for this task, since the problem doesn't specify, and to minimize changes to the server, I'll proceed with client-side translation.
Wait, actually, looking back at the problem, it says "I'd like to add a new feature that allows the user to specify a target language to translate his text. Append the translated text to the original one."
And "An input field is used to specify target languages, such as "en", "ja", "zh-TW ", ...etc."
So, it's clear that the input field is on the client-side, and the user specifies the language for their own messages.
Therefore, handling the translation on the client-side is appropriate.
Moreover, in the server.js, there's no mention of handling translations, so it's better not to modify the server if not necessary.
Thus, I'll stick with the client-side approach.
To summarize, the steps are:
  1. Add an input field in index.html for the target language, with id "target-language" and default value "en".
  2. In chat.js, modify the send message function to:
a. Get the message from the textarea.
b. Get the target language from the input field.
c. If the message is not empty, make a fetch request to the translation API with the message and target language.
d. Upon receiving the response, extract the translated text.
e. Create the full message by appending the translated text to the original message, e.g., ${message} [${translatedText}].
f. Send this full message to the server via socket.emit('send-msg', { m: fullMessage }).
g. If there's an error in translation, just send the original message.
h. Clear the textarea.
Also, I need to handle the case where the target language is not specified, in which case it defaults to "en".
Wait, in the code above, I have const targetLang = document.getElementById('target-language').value || 'en';, so if the input is empty, it will use "en".
But actually, since the input field has a default value of "en", it will always have a value unless the user clears it.
But to be safe, I can keep the fallback to "en".
Additionally, I might want to validate the target language code, but for simplicity, I'll assume the user enters a valid code.
If the code is invalid, the API will probably return an error, and in that case, the catch block will send the original message.
So, that should be fine.
I think this covers the required functionality.
Wait, one more thing: in the problem statement, it says "Note that chat.js and epic.js are not included here.", but since I need to modify chat.js, and it's not provided, I have to assume how it's structured.
But in my explanation, I've provided a plausible way to implement it, so that should be okay.
Alternatively, perhaps I need to provide the modified code snippets.
But since the problem is to "reason step by step", I think explaining the approach is sufficient.
To wrap it up, the main changes are:
  • Add an input field in index.html for the target language.
  • In chat.js, modify the send message logic to include translation before sending.
And that's it.
I don't think I need to modify the server-side code.
Wait, actually, one potential issue: if the message is very long, the translation might take time, and the user might notice a delay. But for a chat application, messages are usually short, so it should be acceptable.
Also, since the translation is done asynchronously, the UI shouldn't freeze; the user can continue typing or doing other things while waiting for the translation.
But in practice, since the send action is tied to the button click, the message will be sent after the translation is complete.
Alternatively, I could send the message immediately and then update it with the translation, but that would be more complicated and might confuse users, so it's better to wait for the translation before sending.
Another consideration: if the user sends multiple messages quickly, the translations might arrive out of order, but since each send is handled separately, and the messages are sent in sequence, it should be fine.
Wait, actually, since each send is triggered by the user clicking the send button, and the next send won't happen until the previous one is processed, it should maintain the order.
Moreover, the server assigns an id to each message, so even if they arrive out of order, the client can display them in the correct order based on the id.
But in this case, since the client sends the messages in order, and the server broadcasts them immediately, it should be okay.
I think I've covered all the necessary aspects.
So, to conclude, by adding an input field for the target language and modifying the client-side send message logic to include translation, I can implement the desired feature.
To add a feature to your real-time chat application that allows users to specify a target language for translating their messages, with the translated text appended to the original message, we’ll use the Google Translate API endpoint "https://translate.googleapis.com/translate_a/single". The source language will be set to "auto", and the target language will default to "en" if not specified. An input field will be added for users to enter target language codes like "en", "ja", "zh-TW", etc. Below, I’ll outline the steps to implement this feature by modifying the client-side code, specifically index.html and chat.js, while keeping the server-side code (server.js) largely unchanged since it already handles message broadcasting effectively.

Step 1: Modify index.html to Add a Target Language Input Field
We need to add an input field to the chat form where users can specify the target language. This field should be placed alongside the existing message input and send button for a seamless user experience. Here’s how to update the <div class="chat-form"> section in index.html:
html
<div class="chat-form">
    <input type="text" id="target-language" placeholder="Target language (e.g., en, ja, zh-TW)" value="en">
    <ul id="emic" style="display:none;"></ul>
    <button id="emic_btn">
        <img src="static/emic/white-smiling-face.png" width="20px" height="20px" title="White Smiling Face">
    </button>
    <textarea id="form_input" class="form-control" data-user-id="2" placeholder="Type something ..." rows="1"></textarea>
    <button id="send">Send</button>
    <ul id="users"></ul>
</div>
Explanation:
  • New Input Field: Added <input type="text" id="target-language" ...> with:
    • id="target-language" for easy access in JavaScript.
    • placeholder to guide users on valid language codes.
    • value="en" as the default target language, fulfilling the requirement.
  • Positioning: Placed before the existing elements to keep the UI intuitive, though styling (via CSS) may be adjusted in style.css if needed.
This allows users to specify their desired translation language before sending a message.

Step 2: Modify chat.js to Handle Translation Before Sending Messages
Since chat.js isn’t provided, I’ll assume it contains logic for sending messages when the "Send" button is clicked or the Enter key is pressed in the textarea. The translation will occur on the client-side before the message is sent to the server via Socket.IO. Here’s how to implement this:
Assumptions About chat.js
  • It uses socket.emit('send-msg', { m: message }) to send messages, based on server.js.
  • The "Send" button (id="send") triggers a send function, likely via an event listener.
Updated Send Logic
We’ll modify the message-sending function to:
  1. Retrieve the original message and target language.
  2. Call the Google Translate API to translate the message.
  3. Append the translated text to the original message.
  4. Send the combined message to the server.
  5. Handle errors gracefully by sending only the original message if translation fails.
Here’s a sample implementation:
javascript
// In chat.js, within the Chat.init or similar setup function
document.getElementById('send').addEventListener('click', function() {
    const message = document.getElementById('form_input').value.trim();
    const targetLang = document.getElementById('target-language').value.trim() || 'en';

    if (!message) return; // Do nothing if the message is empty

    // Make the translation API call
    fetch(`https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${targetLang}&dt=t&q=${encodeURIComponent(message)}`)
        .then(response => response.json())
        .then(data => {
            // Extract translated text from the response (e.g., [["こんにちは","Hello",null,null,1]])
            const translatedText = data[0][0][0];
            const fullMessage = `${message} [${translatedText}]`;
            // Send the combined message to the server
            socket.emit('send-msg', { m: fullMessage });
        })
        .catch(error => {
            console.error('Translation error:', error);
            // If translation fails, send only the original message
            socket.emit('send-msg', { m: message });
        });

    // Clear the input field
    document.getElementById('form_input').value = '';
});
Explanation:
  • Get Inputs:
    • message: From the textarea (id="form_input").
    • targetLang: From the new input (id="target-language"), defaulting to "en" if empty.
  • API Call:
    • URL: https://translate.googleapis.com/translate_a/single with parameters:
      • client=gtx: Required for this endpoint.
      • sl=auto: Auto-detects the source language.
      • tl=${targetLang}: User-specified target language.
      • dt=t: Requests translation.
      • q=${encodeURIComponent(message)}: Encodes the message to handle special characters.
    • Response: A JSON array like [[["こんにちは","Hello",null,null,1]],null,"en"], where data[0][0][0] is the translated text.
  • Message Construction: Combines original and translated text as "original [translated]".
  • Socket Emission: Sends the full message to the server using the existing send-msg event.
  • Error Handling: If the API call fails (e.g., invalid language code, network issues), sends the original message.
  • Clear Input: Resets the textarea after sending.

How It Works
  1. User Interaction:
    • User types a message (e.g., "Hello") in the textarea.
    • User sets the target language (e.g., "ja") in the input field (defaults to "en" if unchanged).
    • User clicks "Send".
  2. Client-Side Processing:
    • chat.js fetches the translation (e.g., "こんにちは" for "Hello" to Japanese).
    • Constructs the full message: "Hello [こんにちは]".
    • Emits it to the server via socket.emit('send-msg', { m: "Hello [こんにちは]" }).
  3. Server-Side Handling:
    • server.js receives the message, adds it to messageCache, and broadcasts it to all users in the "main" room via io.to("main").emit("new-msg", msg).
  4. Display:
    • All users see "Hello [こんにちは]" in the chat, assuming chat.js appends msg.m to the #msgs list.

Considerations
  • Asynchronous Handling: The fetch call is asynchronous, but since sending occurs after translation, message order is preserved.
  • Error Resilience: If translation fails, users still communicate with the original text.
  • Performance: Short messages and a fast API should minimize delays, though high usage might hit API limits (not specified for this endpoint).
  • Security: This uses an unofficial, keyless API. For production, switch to the official Google Cloud Translation API with an API key, ideally handled server-side.
  • UI Feedback: No loading indicator is added for simplicity, but could be implemented if delays are noticeable.

Final Code Changes
index.html (Updated Chat Form)
html
<div class="chat-form">
    <input type="text" id="target-language" placeholder="Target language (e.g., en, ja, zh-TW)" value="en">
    <ul id="emic" style="display:none;"></ul>
    <button id="emic_btn">
        <img src="static/emic/white-smiling-face.png" width="20px" height="20px" title="White Smiling Face">
    </button>
    <textarea id="form_input" class="form-control" data-user-id="2" placeholder="Type something ..." rows="1"></textarea>
    <button id="send">Send</button>
    <ul id="users"></ul>
</div>
chat.js (Sample Send Function)
javascript
document.getElementById('send').addEventListener('click', function() {
    const message = document.getElementById('form_input').value.trim();
    const targetLang = document.getElementById('target-language').value.trim() || 'en';

    if (!message) return;

    fetch(`https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${targetLang}&dt=t&q=${encodeURIComponent(message)}`)
        .then(response => response.json())
        .then(data => {
            const translatedText = data[0][0][0];
            const fullMessage = `${message} [${translatedText}]`;
            socket.emit('send-msg', { m: fullMessage });
        })
        .catch(error => {
            console.error('Translation error:', error);
            socket.emit('send-msg', { m: message });
        });

    document.getElementById('form_input').value = '';
});

Conclusion
With these changes, users can specify a target language via an input field, and their messages will be translated and appended (e.g., "Hello [こんにちは]") before being sent to the server and broadcast to all users. The server requires no modifications, as it simply relays the pre-formatted message. This meets all specified requirements efficiently.