ps:根据版本的不断提升,使用的socket.io的版本也要对应提升。
安装nodejs,到网上在nodejs中安装必要的js,参考npm install --save express
npm install --save socket.io写服务端js,在nodejs中运行的js,运行服务端js: node app.js
-
var app = require('express')();
-
var http = require('http').Server(app);
-
var io = require('socket.io')(http);
-
-
io.on('connection', function(socket){
-
socket.on('chat message', function(msg){
-
console.log(msg);
-
io.emit('chat message', msg);
-
});
-
});
-
-
http.listen(3000, function(){
-
console.log('listening on *:3000');
-
});
-
<!doctype html>
-
<html>
-
<head>
-
<title>Socket.IO chat</title>
-
<style>
-
* { margin: 0; padding: 0; box-sizing: border-box; }
-
body { 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>
-
</head>
-
<body>
-
<ul id="messages"></ul>
-
<form action="">
-
<input id="m" autocomplete="off" /><button>Send</button>
-
</form>
-
-
<script src=""></script>
-
-
<script type="text/javascript" src="jquery.noty.packaged.min.js"></script>
-
<script>
-
var socket = io('');
-
$('form').submit(function(){
-
socket.emit('chat message', $('#m').val());
-
$('#m').val('');
-
return false;
-
});
-
socket.on('chat message', function(msg){
-
$('#messages').append($('
- '
).text(msg));
-
generate('bottomRight', msg);
-
});
-
-
function generate(layout, msg) {
-
var n = noty({
-
text : msg,
-
type : 'alert',
-
dismissQueue: true,
-
layout : layout,
-
theme : 'defaultTheme'
-
});
-
console.log('html: ' + n.options.id);
-
}
-
</script>
-
</body>
-
</html>
java端代码,会用到
-
public class SocketIoTest {
-
public static void main(String[] args) throws URISyntaxException {
-
-
final Socket socket = IO.socket("");
-
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
-
-
@Override
-
public void call(Object... args) {
-
System.out.println("EVENT_CONNECT");
-
socket.emit("chat message", "hi java");
-
socket.disconnect();
-
}
-
-
}).on(Socket.EVENT_ERROR, new Emitter.Listener() {
-
-
@Override
-
public void call(Object... args) {
-
System.out.println("EVENT_ERROR");
-
}
-
-
}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
-
-
@Override
-
public void call(Object... args) {
-
System.out.println("EVENT_DISCONNECT");
-
}
-
-
});
-
socket.connect();
-
System.out.println(socket.connected());
-
-
}
-
}
这样就可能java,html都可以发送了,如果要实现不同频道,那要用到socket.io中的namespace才能完成,暂时没用,所以不写了。
让nodejs在后台运行
npm install forever -g
forever start your_app.js
forever stop your_app.js
forever restart your_app.js
forever start -l forever.log -o out.log -e err.log your_app.js
forever list
阅读(1481) | 评论(0) | 转发(0) |