前端代码
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<link href="../bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="../js/jquery-1.12.3.min.js"></script>
<script src="../bootstrap-3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="vertical-center">
<div class="container">
<!-- 客户端加一个简单的input输入框和一个发送按钮 -->
<form role="form" id="chat_form" onsubmit="sendMessage(); return false;" style="margin-top:100px;">
<div class="form-group">
<input class="form-control" type="text" name="message" id="message" value="" />
</div>
<button type="button" id="send" class="btn btn-primary" onclick="sendMessage();">
发送
</button>
</form>
</div>
</div>
</body>
<script>
//WebSocket实例化
var ws = new WebSocket("ws://localhost:8181");
ws.onopen = function (e) {
//成功连接服务器回调
console.log('客户端(client):与服务器的连接已打开')
}
function sendMessage() {
ws.send($('#message').val());
};
</script>
</html>
后端代码
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<link href="../bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="../js/jquery-1.12.3.min.js"></script>
<script src="../bootstrap-3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="vertical-center">
<div class="container">
<form role="form" id="chat_form" onsubmit="sendMessage(); return false;" style="margin-top:100px;">
<div class="form-group">
<input class="form-control" type="text" name="message" id="message" value="" />
</div>
<button type="button" id="send" class="btn btn-primary" onclick="sendMessage();">
发送
</button>
</form>
</div>
</div>
</body>
<script>
//WebSocket实例化
var ws = new WebSocket("ws://localhost:8181");
ws.onopen = function (e) {
//成功连接服务器回调
console.log('客户端(client):与服务器的连接已打开')
}
function sendMessage() {
ws.send($('#message').val());
};
</script>
</html>