i have a javascript code that setup a websocket connection and have several functions.
The websocket works fine.
but i want to run a javascript function from the script inside the html code.this does not work. if i run the function from a onclick event, then it works fine (see the button).
i have tried the body onload but it does not work.
My goal is: execute the function OnloadFunction if the webpage is loaded. Then it should send a string with websocket.
<!DOCTYPE html><html>
<head>
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
<link rel=\"icon\" href=\"data:,\">
<title>Testpage</title>
<meta charset="UTF-8">
<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center; background-color:#5593F1}
.button { background-color: #195B6A; border: none; color: white; padding: 10px 40px;
text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}
.button2 {background-color: #77878A;}
</style>
<script>
var connection;
connection = new WebSocket('ws://' + window.location.hostname + ':81/');
connection.onopen = function () { connection.send('Connect ' + new Date()); };
connection.onerror = function (error) { console.log('WebSocket Error ', error);};
connection.onmessage = function (e) { console.log('Server: ', e.data);};
function OnloadFunction() {
connection.send('* Test22');
alert("Hello! ");
}
</script>
</head>
<body onload="javascript:OnloadFunction();">
<h1>Testpage</h1>
<p>Suche....</p>
<p><button class="button" onclick="OnloadFunction()">read</button></p>
</body>
</html>
This is a simple test from me but does not work also
<body>
<h1>Test</h1>
<p>Suche...</p>
<p><button class="button" onclick="OnloadFunction()">Lesen</button></p>
<script>
var connection = new WebSocket('ws://' + window.location.hostname + ':81/');
connection.onopen = function () { connection.send('Connect ' + new Date()); };
connection.onerror = function (error) { console.log('WebSocket Error ', error);};
connection.onmessage = function (e) { console.log('Server: ', e.data);};
connection.send('* Test22');
</script>
</body>
What is wrong? How can i execute the function OnloadFunction() in the html code if the webside is loaded?
EDIT1:
Thank you for all the suggestions. i have tried much different ways but nothing works.
Now I am close to a solution but I do not understand the new error.
The function start() is executet because of window.onload=start;
But the code after connection.onmessage = function(evt) { console.log(evt);};
is only executet if the alert("TEST___"); is in the code. if i delete this line then the code after that is not executet. Why is the code not executet without alert("TEST___"); ?? With the button onclick all works well without the alert.
Here my code websock2.js (the alters are only for testing):
var connection;
function OnloadFunction() {
connection.send('* Test22'+' x');
alert("LOADED! ");
}
function start() {
alert("Start! ");
connection = new WebSocket('ws://' + window.location.hostname + ':81/');
<!-- connection = new WebSocket('ws://192.168.1.5:81/',['arduino']); -->
connection.onopen = function () { connection.send('Connect ' + new Date()); };
connection.onerror = function (error) { console.log('WebSocket Error ', error);};
connection.onmessage = function(evt) { console.log(evt);};
alert("TEST___");
connection.send('* Test22'+' x');
console.log('effekt: ');
alert("LOADED! ");
}
window.onload=start;
Here my html code:
<!DOCTYPE html><html>
<head>
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
<link rel=\"icon\" href=\"data:,\">
<title>Testpage</title>
<meta charset="UTF-8">
<script src="websock2.js" async></script>
<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center; background-color:#5593F1}
.button { background-color: #195B6A; border: none; color: white; padding: 10px 40px;
text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}
.button2 {background-color: #77878A;}
</style>
</head>
<body>
<h1>Testpage</h1>
<p>read....</p>
<p><button class="button" onclick="OnloadFunction()">Lesen</button></p>
</html>
Related
Hello lately i've been working with APIs to get the hang of them through the usual weather app project BUT i'm pretty much still a beginner in javascript and i was wondering how to add a background image that matches the weather report of the city selected by the user.
I wanted to create many classes in css, each called like the weather (ex: .clear, .clouds,.rain etc...) and then use a classList.add() method to change it each time depending on the openWeatherMap data. I tried adding something like document.getElementsByTagName("body")[0].classList.add(weatherValue); inside the .then promise but it doesn't work. Can somebody help me? If there's a much simpler way i'd like to hear about it too :) Thank you so much
var button = document.querySelector(".button");
var inputValue = document.querySelector(".inputValue");
var cityName = document.querySelector(".name");
var weather = document.querySelector(".weather");
var desc = document.querySelector(".desc");
var temp = document.querySelector(".temp");
var humi = document.querySelector(".humi");
button.addEventListener("click", function() {
fetch("https://api.openweathermap.org/data/2.5/weather?q="+inputValue.value+"&appid={myapikey}")
.then(response => response.json())
.then(data => {
var nameValue = data['name'];
var weatherValue = data['weather'][0]['main'];
var tempValue = data['main']['temp'];
var descValue = data['weather'][0]['description'];
var humiValue = data['main']['humidity'];
cityName.innerHTML = nameValue;
weather.innerHTML = weatherValue; // this gives "clear" "clouds" etc to <p> element
desc.innerHTML = descValue;
temp.innerHTML = "Temperature: " + tempValue;
humi.innerHTML = "Humidity: " + humiValue;
})
.catch(err => alert("Wrong city name!"))
})
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: "Nunito", sans-serif;
background-repeat: no-repeat;
background-size: cover;
}
.input {
text-align: center;
margin: 100px 0;
}
input[type="text"] {
height: 50px;
width: 600px;
background: #e7e7e7;
font-family: "Nunito", sans-serif;
font-weight: bold;
font-size: 20px;
border: none;
border-radius: 2px;
padding: 10px 10px;
}
input[type="submit"] {
height: 50px;
width: 100px;
background: #e7e7e7;
font-family: "Nunito", sans-serif;
font-weight: bold;
font-size: 20px;
border: none;
border-radius: 2px;
}
.display {
text-align: center;
}
.clear {
/* background image here */
}
.clouds {
/* another background image here */
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="weather_app.css">
</head>
<body>
<div class="input">
<input type="text" class="inputValue" placeholder="Enter a city">
<input type="submit" value="Submit" class="button">
</div>
<div class="display">
<h1 class="name"></h1>
<p class="weather"></p>
<p class="desc"></p>
<p class="temp"></p>
<p class="humi"></p>
</div>
<script src= "weather_app.js"></script>
</body>
</html>
I did a project like this not long ago, https://github.com/Kroplewski-M/Weather-App , I used the openWeater API. I did this:
function setBackground(weather) {
if (weather == "Rain") {
background.src = "./resources/rainy-weather.jpg";
} else if (weather == "Snow") {
background.src = "./resources/snowy-weather.jpg";
} else if (weather == "Clear") {
background.src = "./resources/sunny-weather.jpg";
} else if (weather == "Clouds") {
background.src = "./resources/cloudy-weather.jpg";
}
}
The openWeather API returns what condition the weather is so you can just if statement on what the condition is and set the background accordingly
I am writing copy button for code-blocks, but the button can not handle "copy" event.
The buttons are created with createElement method, and event added to the buttons with addEventListener to the buttons, before appending to the blocks, through foreach loop.
JSFiddle Link of the blocks
Create Button code:
const textspan = document.createElement("SPAN");
const bgbutton = document.createElement("BUTTON");
bgbutton.classList.add("btnCopy", "badge");
bgbutton.innerText = "copy";
bgbutton.addEventListener('click', copytextHandle);
textspan.appendChild(bgbutton);
const codeSyn = document.querySelectorAll("pre");
codeSyn.forEach(function(el) {
el.insertAdjacentElement('afterbegin', textspan);
})
In my text, I have three blocks, but only one button is visible(last), first two blocks has no button.
Also, the click event, and functionality can not implemented with click hook. The problem is straight about, click event, please mention which causing the error.
window.addEventListener('load', function() {
var y = document.querySelectorAll("pre code");
for(var i = 0; i < y.length; i++) {
y[i].innerHTML = y[i].innerHTML.replace(/^\r?\n/, "");
}
const textspan = document.createElement("SPAN");
const bgbutton = document.createElement("BUTTON");
bgbutton.classList.add("btnCopy", "badge");
bgbutton.innerText = "copy";
bgbutton.addEventListener('click', copytextHandle);
textspan.appendChild(bgbutton);
const codeSyn = document.querySelectorAll("pre");
codeSyn.forEach(function(el) {
el.insertAdjacentElement('afterbegin', textspan);
})
})
const copytextHandle = (e) => {
const codeBlock = document.querySelectorAll(".hljs-ln")[e.target.dataset.idx];
const text = codeBlock
.innerText
.trim()
.replace(/\s+/g, " ")
.replace(/}/g, "}\n")
.replace(/{ /g, "{\n ")
.replace(/;/g, ";\n ")
copySuccess.classList.remove('hide');
navigator.clipboard.writeText(text).then(() => setTimeout(() => bgbutton.innerHTML("Copied"),200),
(e) => {
console.log('Error writing to the clipboard', e.message);
copySuccess.classList.add('hide');
}
);
};
span > button.btnCopy {
position: absolute;
right: 0;
margin-top: 0.6rem;
}
pre {
position: relative;
}
.btnCopy{border:none; background-color: #e8e8e8;}
/*background-color:a5a5a5, 9c9c9c*/
.btnCopy:hover{background-color: #585858}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Testing HighlightJS</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/styles/routeros.min.css">
</head>
<body>
<h3>Testing HighlightJS Multiple blocks</h3>
<h4>First Code block</h4>
<pre><code class="language-css">
.class{
font-size: 0.85rem;
font-weight: 600;
font-family: monospace;
}
h1 .header{
font-size: 1.5rem;;
font-family: Arial;
}
</code></pre>
<h4>Second Code block</h4>
<pre><code class="language-css">
.class{
font-size: 0.85rem;
font-weight: 600;
font-family: monospace;
}
h1 .header{
font-size: 1.5rem;;
font-family: Arial;
}
</code></pre>
<h4>Third Code block</h4>
<pre><code class="language-css">
.class{
font-size: 0.85rem;
font-weight: 600;
font-family: monospace;
}
h1 .header{
font-size: 1.5rem;;
font-family: Arial;
}
</code></pre>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/languages/css.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlightjs-line-numbers.js/2.6.0/highlightjs-line-numbers.min.js"></script>
<script>hljs.highlightAll(); hljs.initLineNumbersOnLoad();</script>
</body>
</html>
After clicking the button copy you can get to a <table> element which is inside one of your <code> elements with this code:
const codeBlock = e.target.parentNode.nextSibling.children[0];
Once that is applied, the text within <code> gets copied to the variable text which we can see by running the code below and checking the console output.
The copy buttons now appear on all <code> blocks. I've added the code to create the button and span inside the codeSyn.forEach(function(el) { ... }, so that new elements are created for every <pre> that you are iterating through.
Another problem that arises is:
Uncaught ReferenceError: copySuccess is not defined
To resolve this error you should assign an HTML element that has class hide to the variable copySuccess so that this works:
copySuccess.classList.remove('hide');
Check the below code:
window.addEventListener('load', function() {
var copySuccess = document.getElementById("copySuccess");
var y = document.querySelectorAll("pre code");
for(var i = 0; i < y.length; i++) {
y[i].innerHTML = y[i].innerHTML.replace(/^\r?\n/, "");
}
const codeSyn = document.querySelectorAll("pre");
codeSyn.forEach(function(el) {
const textspan = document.createElement("SPAN");
const bgbutton = document.createElement("BUTTON");
bgbutton.classList.add("btnCopy", "badge");
bgbutton.innerText = "copy";
bgbutton.addEventListener('click', copytextHandle);
textspan.appendChild(bgbutton);
el.insertAdjacentElement('afterbegin', textspan);
})
})
const copytextHandle = (e) => {
const codeBlock = e.target.parentNode.nextSibling.children[0];
const text = codeBlock
.innerText
.trim()
.replace(/\s+/g, " ")
.replace(/}/g, "}\n")
.replace(/{ /g, "{\n ")
.replace(/;/g, ";\n ");
navigator.clipboard.writeText(text).then(() => setTimeout(() => e.target.innerHTML = "copied",2000),
(e) => {
console.log('Error writing to the clipboard', e.message);
}
);
};
span > button.btnCopy {
position: absolute;
right: 0;
margin-top: 0.6rem;
}
pre {
position: relative;
}
.hide {
display: none;
}
.btnCopy{border:none; background-color: #e8e8e8;}
/*background-color:a5a5a5, 9c9c9c*/
.btnCopy:hover{background-color: #585858}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Testing HighlightJS</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/styles/routeros.min.css">
</head>
<body>
<h3>Testing HighlightJS Multiple blocks <span id="copySuccess" class="hide">Copied...</span></h3>
<h4>First Code block</h4>
<pre><code class="language-css">
.class{
font-size: 0.85rem;
font-weight: 600;
font-family: monospace;
}
h1 .header{
font-size: 1.5rem;
font-family: Arial;
}
</code></pre>
<h4>Second Code block</h4>
<pre><code class="language-css">
.class{
font-size: 0.85rem;
font-weight: 600;
font-family: monospace;
}
h1 .header{
font-size: 1.5rem;
font-family: Arial;
}
</code></pre>
<h4>Third Code block</h4>
<pre><code class="language-css">
.class{
font-size: 0.85rem;
font-weight: 600;
font-family: monospace;
}
h1 .header{
font-size: 1.5rem;
font-family: Arial;
}
</code></pre>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/languages/css.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlightjs-line-numbers.js/2.6.0/highlightjs-line-numbers.min.js"></script>
<script>hljs.highlightAll(); hljs.initLineNumbersOnLoad();</script>
</body>
</html>
What is happeninig is you're moving the same button in a loop all the way to last pre. Use eg. cloneNode to make a new button per pre element.
simple move scenario (https://jsfiddle.net/jtg6fczd/)
document.querySelector("div").append(button) // adds button to div
document.body.append(button) // moves button out of div
I'm trying to fetch a 5-day weather forecast by using JS Fetch API, though I'm passing cnt=5 as stated in the documentation, Still, I'm getting only current weather. Am I missing anything?
fetch('https://api.openweathermap.org/data/2.5/weather?q=' + city+ '&appid=' + key+'&cnt=5')
I have done enough research and couldn't able to figure out where exactly I'm doing a mistake. Any help is appreciated.
const key = '**** Your API Key Here ****';
function weatherForecast(city) {
fetch('https://api.openweathermap.org/data/2.5/weather?q=' + city+ '&appid=' + key+'&cnt=5')
.then(function(resp) {
return resp.json()
})
.then(function(data) {
console.log('--->'+(JSON.stringify(data)));
drawWeather(data);
})
.catch(function() {
// catch any errors
});
}
function drawWeather( d ) {
var celcius = Math.round(parseFloat(d.main.temp)-273.15);
var fahrenheit = Math.round(((parseFloat(d.main.temp)-273.15)*1.8)+32);
var description = d.weather[0].description;
document.getElementById('description').innerHTML = description;
document.getElementById('temp').innerHTML = fahrenheit + '°';
document.getElementById('location').innerHTML = d.name+' '+d.sys.country;
}
//Event Listeners on button click
document.addEventListener("DOMContentLoaded", () => {
// Handling button click
document.querySelector(".button-search").addEventListener("click", () => {
const searchedCity = document.querySelector('.text-search');
console.log(searchedCity.value);
if(searchedCity.value){
weatherForecast(searchedCity.value);
}
})
});
body {
font-family: 'Montserrat', sans-serif;
font-weight: 400;
font-size: 1.3em;
height: 100vh;
}
h1 {
margin: 0 auto;
font-size: 2.2em;
text-align: center;
font-size: 10em;
}
.main-container,.search-component{
display: flex;
align-items: center;
justify-content: center;
margin: 2em;
}
.text-search{
width: 100%;
max-width: 280px;
padding: 10px 15px;
border: solid blueviolet;
color: #313131;
font-size: 20px;
font-weight: 300;
transition: 0.2s ease-out;
}
.button-search{
font-size: 32px;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Current Weather</title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,900" rel="stylesheet">
<link href="style.css" rel="stylesheet">
</head>
<body>
<div class="search-component">
<input type="text" autocomplete="off" class="text-search" placeholder="Type the City Name..." >
<input type="button" class="button-search" value="Search">
</div>
<div class="main-container">
<div>
<div id="description"></div>
<h1 id="temp"></h1>
<div id="location"></div>
</div>
<div>
<script src="main.js"></script>
</body>
</html>
Here is the JSON response I'm getting.
{
"coord":{"lon":-74.01,"lat":40.71},
"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],
"base":"stations",
"main":{
"temp":303.24,
"feels_like":306.4,
"temp_min":301.48,
"temp_max":304.82,
"pressure":1011,
"humidity":74
},
"visibility":10000,
"wind":{"speed":4.6,"deg":260},
"clouds":{"all":1},
"dt":1596415305,
"sys":{
"type":1,
"id":4610,
"country":"US",
"sunrise":1596362046,
"sunset":1596413419
}
"timezone":-14400,
"id":5128581,
"name":"New York",
"cod":200
}
For a 5-day weather forecast you need call /forecast instead of /weather endpoint.
Example:
https://api.openweathermap.org/data/2.5/forecast?q=New%20York&appid=<your-api-key>&cnt=5
This is my first AJAX and my first use of .php file. I'm following an exercise in the text and it's not working. I tried to use the alert function as many times as possible to check what is feeding in to variables and functions, but I'm really unsure what's going on in the background. I checked the Yahoo! Weather RSS feed which is supposed to give this website some information ("http://weather.yahooapis.com/forecastrss?p=94558") and I do see the "item" tag. The console keeps saying "Cannot call method 'getElementsByTagName"!! Appreciate any input in advance....
<!DOCTYPE html PUBLIC "-\\W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Weather Report</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<style type="text/css">
html {
height: 100%;
margin: 0;
padding: 0;
}
body
{
height: 100%;
margin: 0;
padding: 0;
}
a { color: #91c056; }
a:link { color: #515151; text-decoration: none; }
a:visited { color: #515151; text-decoration: none; }
a.back:hover { color: #6eece3; }
#content-pane{
font-family: Courier New, monospace;
letter-spacing: -0.05em;
font-size: 15px;
line-height: 23px;
float:left;
width:100%;
padding-left: 5%;
padding-top: 5%;
}
#headline
{
font-family: Helvetica, "Helvetica Neue", Arial, sans-serif;
font-weight: bold;
letter-spacing: -0.05em;
font-size: 60px;
line-height: 60px;
color: #323232;
text-align: left;
}
</style>
<script type="text/javascript">
/* <![CDATA[ */
var weatherRequest = false;
function getRequestObject(){
try {
httpRequest = new XMLHttpRequest();
}
catch (requestError){
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (requestError) {
try{
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (requestError){
window.alert("Your browser does not support AJAX!");
return false;
}
}
}
return httpRequest;
}
function weatherUpdate(){
if(!weatherRequest)
weatherRequest = getRequestObject();
var zip = document.forms[0].zip.value;
weatherRequest.abort();
weatherRequest.open("get", "WeatherReport.php?zip=" + zip, true);
weatherRequest.send(null);
weatherRequest.onreadystatechange=fillWeatherInfo;
}
function fillWeatherInfo(){
if (weatherRequest.readyState == 4 && weatherRequest.status == 200){
var weather = weatherRequest.responseXML;
var weatherItems=weather.getElementsByTagName("item");
if (weatherItems.length > 0){
for (var i=0; i<weatherItems.length; ++i){
var curHeadline = weatherItems[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
var curLink = weatherItems[i].getElementsByTagName("link")[0].childNodes[0].nodeValue;
var curPubDate = weatherItems[i].getElementsByTagName("pubDate")[0].childNodes[0].nodeValue;
var curDesc = weatherItems[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
var weatherSpot = document.getElementById('weatherPara');
var curStory = "<a href='" + curLink + "'>" + curHeadline + "</a><br />";
curStory += "<span style='color: gray'>";
curStory += curDesc + "<br />";
weatherSpot.innerHTML = curStory;
}
}
else
window.alert("Invalid ZIP code.");
}
}
/* }]> */
</script>
</head>
<body onload ="weatherUpdate()">
<div id="content-pane">
go back
<div id="headline">Weather Report</div>
<br />
<br />
<br />
<br />
<form method="get" action="">
<p>ZIP code <input type="text" name="zip" value="94558"/> <input type="button" value="Check Weather" onclick="weatherUpdate()" /></p>
</form>
<p id="weatherPara"></p>
</div>
</body>
</html>
Below is the WeatherReport.php file.
<?php
$Zip = $_GET["zip"];
$WeatherURL
= "http://weather.yahooapis.com/forecastrss?p=" . $Zip;
header("Content-Type: text/xml");
header("Content-Length: " . strlen(file_get_contents($WeatherURL)));
header("Cache-Control: no-cache");
readfile($WeatherURL);
?>
Try adding your WeatherReport.php in form action. You have to specify your php file in you action otherwise the form will point to the same file.
In your function fillWeatherInfo, you haven't passed it any parameters. Therefore, I believe weatherRequest.responseXML is an empty object.
In your onreadystatechange property, you need to pass in the parameters of the AJAX response to the handler.
When I run the node server, the console indicates "info - socket.io started". However, it never detects a connection from the client side. I believe it is an issue with the installation of socket.io as I am running a Windows 7 machine...
When I attempt to connect to the server from the client side my server console indicates "debug - served static content /lib/socket.io.js".
Anyone have any suggestions how I can get socket io to succesfully connect from the client side on my Windows 7 machine?
Right now, I have the socket.io folder located in the following directory:
nodejs/node_modules/socket.io/
I have the following code on the server side for a tcp server in node:
var http = require('http'),
sys = require('util'),
fs = require('fs'),
io = require('socket.io');
console.log('Creating server...');
var server = http.createServer(function(request, response) {
response.writeHead(200, {
'Content-Type': 'text/html'
});
var rs = fs.createReadStream(__dirname + '/template.html');
sys.pump(rs, response);
});
var socket = io.listen(server);
socket.on('connection', function(client) {
var username;
console.log('New client connected.');
client.send('Welcome to this socket.io chat server!');
client.send('Please input your username: ');
client.on('message', function(message) {
if (!username) {
username = message;
client.send('Welcome, ' + username + '!');
return;
}
socket.broadcast(username + ' sent: ' + message);
});
});
server.listen(20000);
This is the code on the client side:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chat</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript" src="http://localhost:20000/socket.io/lib/socket.io.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var entry_el = $('#entry');
var socket = new io.Socket('localhost', {port: 20000});
socket.connect();
console.log('connecting...');
socket.on('connect', function() {
console.log('connect');
});
socket.on('message', function(message) {
var data = message.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");
$('#log ul').append('<li>' + data + '</li>');
window.scrollBy(0, 1000000000000000);
entry_el.focus();
});
entry_el.keypress(function(event) {
if (event.keyCode != 13) return;
var msg = entry_el.attr('value');
if (msg) {
socket.send(msg);
entry_el.attr('value', '');
}
});
});
</script>
<style type="text/css">
body {
background-color: #666;
color: fff;
font-size: 14px;
margin: 0;
padding: 0;
font-family: Helvetica, Arial, Sans-Serif;
}
#log {
margin-bottom: 100px;
width: 100%;
}
#log ul {
padding: 0;
margin: 0;
}
#log ul li {
list-style-type: none;
}
#console {
background-color: black;
color: white;
border-top:1px solid white;
position: fixed;
bottom: 0;
width: 100%;
font-size: 18px;
}
#console input {
width: 100%;
background-color: inherit;
color: inherit;
font-size: inherit;
}
</style>
</head>
<body>
<h1>Chat</h1>
<div id="log"><ul></ul></div>
<div id="console">
<input type="text" id="entry" />
</div>
</body>
</html>
Thanks!
Your socketio js should be inside the following path
http://{host:port}/socket.io/socket.io.js
In your case you need to include as follows
<script type="text/javascript" src="http://localhost:20000/socket.io/lib/socket.io.js"></script>