Hello Flask Socket.IO [3]


Hello Flask Socket.IO 系列文章三。本文基于 Flask Socket.IO 实现聊天室的功能。

相关文章:
Hello Flask Socket.IO [1]
Hello Flask Socket.IO [2]
相关 Github 源码

版权声明:本文为 frendy 原创文章,可以随意转载,但请务必在明确位置注明出处。


服务器端


基于 Flask SocketIO 自带的 Room 概念来实现,分别实现加入房间、发送消息和离开房间三个监听即可。

1.加入房间的事件监听处理:
@socketio.on('joined')
def joined(message):
	"""Sent by clients when they enter a room.
	A _joined message is broadcast to all people in the room."""
	global GLOBAL_NUM_USERS
	GLOBAL_NUM_USERS = GLOBAL_NUM_USERS + 1
	print(message)
	session['name'] = message['name']
	session['room'] = message['room']
	room = session.get('room')
	join_room(room)
	print(session)
	emit('_joined', {'user_name': session.get('name'), 'num_users' : GLOBAL_NUM_USERS}, room=room)
2.发送消息的事件监听处理:
@socketio.on('message')
def message(message):
	"""Sent by a client when the user entered a new message.
	The _message is sent to all people in the room."""
	room = session.get('room')
	print(session)
	emit('_message', {'user_name': session.get('name'), 'message' : message['message']}, room=room, include_self=False)
3.离开房间的事件监听处理:
@socketio.on('left')
def left(message):
	"""Sent by clients when they leave a room.
	A _left message is broadcast to all people in the room."""
	global GLOBAL_NUM_USERS
	GLOBAL_NUM_USERS = GLOBAL_NUM_USERS - 1
	room = session.get('room')
	leave_room(room)
	print(session)
	emit('_left', {'user_name': session.get('name'), 'num_users' : GLOBAL_NUM_USERS}, room=room)

Android 端


Android Client 端则添加了一个 FragmentChat 页面来实现聊天室的基本交互,具体功能逻辑处理可以参考 ChatHelper

image

1.主要的逻辑处理对应服务器端的三个监听,用于向服务器端发送消息:
public void attemptLogin(String username, String room) {
	...
	JSONObject data = new JSONObject();
	data.put("name", username);
	data.put("room", room);
	mSocket.emit("joined", data);
}

public void attemptSend() {
	...
	JSONObject data = new JSONObject();
	data.put("message", message);
	mSocket.emit("message", data);
}

public void leave() {
	...
	mSocket.emit("left", "1");
	mSocket.disconnect();
}
2.主要的监听处理如下,用于响应服务器端发送过来的消息:
mSocket.on(Socket.EVENT_CONNECT,onConnect);
mSocket.on(Socket.EVENT_DISCONNECT,onDisconnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.on("_message", onNewMessage);
mSocket.on("_joined", onUserJoined);
mSocket.on("_left", onUserLeft);


欢迎来撩

frendy

It will shine for us...