一个功能很简单的网页即时通讯,用websocket实现
因为是菜鸟,现在一点方向都没有,现在提出几个疑问.
1.有个Tomact服务器,上传html文件到服务器路径有没有什么特别的要求?因为websocket有服务器端处理代码,
是用java写的,java文件是不是先编译成class文件再上传啊?路径有没有特别的要求?
2.websocket服务器端处理代码怎么写?(大致)
------解决方案--------------------
<script type="text/javascript">
// Create a socket
var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket;
var socket = new WS('@@{WebSocket.ChatRoomSocket.join(user)}')
// Display a message
var display = function(event) {
$('#thread').append(tmpl('message_tmpl', {event: event}));
$('#thread').scrollTo('max')
}
// Message received on the socket
socket.onmessage = function(event) {
var parts = /^([^:]+):([^:]+)(:(.*))?$/.exec(event.data)
display({
type: parts[1],
user: parts[2],
text: parts[4]
})
}
$('#send').click(function(e) {
var message = $('#message').val()
$('#message').val('')
socket.send(message)
});
$('#message').keypress(function(e) {
if(e.charCode == 13
------解决方案--------------------
e.keyCode == 13) {
$('#send').click()
e.preventDefault()
}
})
</script>
------解决方案--------------------
服务器端:
package controllers;
import play.*;
import play.mvc.*;
import play.libs.*;
import play.libs.F.*;
import play.mvc.Http.*;
import static play.libs.F.*;
import static play.libs.F.Matcher.*;
import static play.mvc.Http.WebSocketEvent.*;
import java.util.*;
import models.*;
public class WebSocket extends Controller {
public static void room(String user) {
render(user);
}
public static class ChatRoomSocket extends WebSocketController {
public static void join(String user) {
ChatRoom room = ChatRoom.get();
// Socket connected, join the chat room
EventStream<ChatRoom.Event> roomMessagesStream = room.join(user);
// Loop while the socket is open
while(inbound.isOpen()) {
// Wait for an event (either something coming on the inbound socket channel, or ChatRoom messages)
Either<WebSocketEvent,ChatRoom.Event> e = await(Promise.waitEither(
inbound.nextEvent(),
roomMessagesStream.nextEvent()
));