Created
June 10, 2016 13:28
-
-
Save lv7777/3a2ac77016b528c4be9a844b94f6812f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http=require("http"); | |
var socketio=require("socket.io");//mandatory. | |
var fs=require("fs") | |
var server=http.createServer(function(req, res) { | |
res.writeHead(200, {'Content-Type' : 'text/html'}); | |
res.end(fs.readFileSync(__dirname + '/index.html', 'utf-8')); | |
}); | |
server.listen(3000); | |
//鯖をoverwrite? overload? | |
//返り値でイベント駆動するのでとっておく | |
var io=socketio.listen(server); | |
io.sockets.on("connection",function(socket){ | |
//こんなかでイベント登録か。 | |
//client to server. | |
socket.on("client_to_server",function(data){ | |
//dataには送られてきたdataが入ってるんだな。 | |
//clientから鯖にデータが送られてきた時すべてのclientに受け取ったdataを送る。 | |
io.sockets.emit("server_to_client",{value:data.value}) | |
}); | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>websocket-chat</title> | |
<link rel="stylesheet" | |
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> | |
<!-- 1.socket.ioが自動で/socket.ioフォルダとその下にsocket.io.jsを作るのでそいつをfetch --> | |
<script type="text/javascript" src="/socket.io/socket.io.js"></script> | |
</head> | |
<body> | |
<div class="container"> | |
<h1>WebSocket-Chat</h1> | |
<form action="" class="form-inline"> | |
<div class="form-group"> | |
<label for="msgForm">Message:</label> | |
<input type="text" name="" id="msgForm" class="form-control"> | |
</div> | |
<button type="submit" class="btn btn-primary">送信</button> | |
</form> | |
<div id="chatLogs"></div> | |
</div> | |
<script type="text/javascript"> | |
var clientsocket= io.connect(); | |
//clientの場合は接続を待たなくてももう起動しているわけなのでそのままイベント登録してもok | |
clientsocket.on("server_to_client",function(data){ | |
appendMsg(data.value) | |
}) | |
function appendMsg(text) { | |
$("#chatLogs").append("<div>" + text + "</div>"); | |
} | |
$("form").submit(function(e){ | |
var message = $("#msgForm").val(); | |
$("#msgForm").val(''); | |
//きほんてきに送信は.emitを使う。 | |
clientsocket.emit("client_to_server", {value : message}); | |
e.preventDefault(); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment