Skip to content

Instantly share code, notes, and snippets.

@AlperRehaYAZGAN
Created August 9, 2019 09:39
Show Gist options
  • Save AlperRehaYAZGAN/05ab853bbc7c369fedfb5d398d3787fe to your computer and use it in GitHub Desktop.
Save AlperRehaYAZGAN/05ab853bbc7c369fedfb5d398d3787fe to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Socket.io Sample Page</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: #ebebeb;
font: 13px Helvetica, Arial;
}
form {
background: #000;
padding: 3px;
position: fixed;
bottom: 0;
width: 100%;
}
form input {
border: 0;
padding: 10px;
width: 90%;
margin-right: .5%;
}
form button {
width: 9%;
background: rgb(130, 224, 255);
border: none;
padding: 10px;
}
#messages {
list-style-type: none;
margin: 0;
padding: 0;
}
#messages li {
padding: 5px 10px;
}
#messages li:nth-child(odd) {
background: #eee;
}
</style>
<script src="/socket.io/socket.io.js"></script>
<!-- Bunu kesinlikle yazmamız gerekiyor çünkü birazdan yazacağımız kodlar bu dosyayı referans alarak çalışacaktır. -->
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<!-- İşlerimizi çok kolaylaştırdığı için jquery kütüphanesini çağırıyoruz. -->
</head>
<body>
<ul id="messages"></ul><!-- Gelen mesajları yazdırmak için bir liste oluşturuyoruz. -->
<form action="">
<input id="m" autocomplete="off" /><button>Gönder</button>
<!-- Forma yazı yazdıktan sonra gönder butonu ile gönderiyoruz. -->
</form>
<script>
var socket = io(); // Kullanıcı tarafında da bağlantı nesnemizi oluşturuyoruz.
$(function () {
$('form').submit(function (e) { /* Formu göndermek için alıyor. */
e.preventDefault(); // Sayfanın yenilenmesini engelliyor.
socket.emit('chat message', $('#m').val()); /* Yazdığımız mesajı alıyor ve socket antenine chat message kodu ile dışarı yayınlıyor. */
$('#m').val(''); // Ardından ise bu mesaj kısmını gönderdiği için geri boş hale getiriyor.
return false;
});
socket.on('chat message', function (msg) { /* yukarıda emit diyerek mesajı yayınladığımız gibi eğer bana chat message başlığı ile bir mesaj gelirse onu ekrana yazdır diyoruz. */
$('#messages').append($('<li>').text(msg)); /* gelen mesajı message id'sine sahip elemente text olarak yazdır diyoruz. */
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment