初级视频编辑室|草蜢非编论坛|初级视编室|草蜢视频编辑|会声会影|威力导演|电子相册
标题:
flash与后台数据交换方法整理4-XMLSocket篇
[打印本页]
作者:
五星上将
时间:
2014-11-26 21:55
标题:
flash与后台数据交换方法整理4-XMLSocket篇
XMLSocket主要用于与服务端进行即时通信,目前的应用领域主要是Flash文本聊天和Flash在线游戏等方面。
XMLSocket的优点:
1、能和服务端即时通信;
2、Flash Player 5.0以上的版本内置类,不需另装组件或插件;
3、因为XMLSocket就是相当于一个Socket客户端,所以一般的中间件都支持的(如java,.Net等)
XMLSocket的缺点:
1、XMLSocket只能传字符串或xml格式的文本,数据类型单一;
2、XMLSocket服务端自行开发的话,需要对Socket技术比较了解才行,好在网上有现成的服务端软件(商业的XMLSocket Server 有Unity、Fortress;开源的XMLSocket Server 有Oregano Multiuser Server);
3、还有就是XMLSocket的80端口与flash安全策略问题。(网上有一个解决方法,不知是否可行,请自行验证)
//=======================================;
// Flash客户端(以Flash文本聊天为例);
//=======================================;
var paramObj:Object = new Object();
//命令分隔符;
paramObj.CommandDelimiters = "-@@##@@-";
//用户列表分隔符;
paramObj.PeopleDelimiters = "-@#@-";
//建立XMLSocket对象;
var socket:XMLSocket = new XMLSocket();
//连接状态事件;
socket.onConnect = function(success) {
trace("socket.onConnect:"+success);
if (!success) {
trace("服务器连接失败,请检查网络状态!");
}
};
//关闭事件;
socket.onClose = function() {
trace("服务端已关闭!");
logoutChat();
};
//数据通信事件;
socket.onData = function(src) {
//trace("socket.onData:"+src);
doCommand(getCmdArrayByMsg(trim(src)));
};
//用户登录;
function loginChat():Void {
//连接Socket服务端;
socket.connect(“localhost”, “8888”);
sendSocket("INFO"+paramObj.CommandDelimiters+msg);
}
//用户注销;
function logoutChat(b:Boolean):Void {
sendSocket("QUIT");
}
//显示聊天信息;
function showChat(msg:String):Void {
trace(“聊天信息:”+msg);
}
//发送聊天信息;
function sendChat(msg:String):Void{
sendSocket("MSG"+paramObj.CommandDelimiters+msg+paramObj.CommandDelimiters+msg);
}
//向服务端发送信息;
function sendSocket(msg:String):Void {
socket.send(msg+"\r");
}
//处理服务端返回信息;
function getCmdArrayByMsg(msg:String):Array {
if (msg.charCodeAt(0) == 13 && msg.charCodeAt(1) == 10) {
msg = msg.substr(2);
}
return msg.split(paramObj.CommandDelimiters);
}
function doCommand(arr:Array):Void {
switch (arr[0]) {
case "MSG" :
showChat(arr[1]);
break;
case "TAKEN" :
trace("你的登录名已经有了,请重新换一个登录名!");
break;
case "PEOPLE" :
doPeople(arr[1]);
break;
}
}
//显示在线用户列表;
function doPeople(msg:String):Void {
var people_arr:Array = msg.split(paramObj.PeopleDelimiters);
trace(people_arr);
}
//上面与XMLSocket有关的主要代码,显示方面自己添加相关组件就行了!
//有一个注意点,在flash向服务端发送的命令的最后一定要加上“\r”,否则服务端无法收到消息(我的服务端是用Java开发的)
//=======================================;
// 服务端代码(我用java开发的,其他版本自行研究);
// ChatServer.java
//=======================================;
package com.klstudio.socket.chat;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
//import com.klstudio.util.Logger;
/**
* @author kinglong
*
* TODO 要更改此生成的类型注释的模板,请转至窗口-首选项- Java -代码样式-代码模板
*/
public class ChatServer {
//private Logger logger;
private static Vector clients = new Vector();
private static ServerSocket server = null;
private static Socket socket = null;
public static String CommandDelimiters = "-@@##@@-";
public static String PeopleDelimiters = "-@#@-";
public ChatServer() {
}
public static void notifyRoom() {
StringBuffer people = new StringBuffer("PEOPLE"+CommandDelimiters+"所有的人");
for (int i = 0; i < clients.size(); i++) {
Client client = (Client) clients.elementAt(i);
people.append(PeopleDelimiters+client.getClientName());
}
sendClients(people);
}
public staticboolean checkName(Client newClient){
for(int i=0;i<clients.size();i++){
Client client = (Client) clients.elementAt(i);
if(client != newClient && client.getClientName().equals(newClient.getClientName())){
return false;
}
}
return true;
}
public static void closeAll(){
while(clients.size()>0){
Client client = (Client) clients.firstElement();
try {
client.getClientSocket().close();
} catch (IOException e) {
// TODO 自动生成 catch 块
//Logger logger = new Logger(System.out);
//logger.log("错误-" + e.toString());
} finally {
clients.removeElement(client);
}
}
}
public static synchronized void disconnect(Client client) {
client.send(new StringBuffer("QUIT"));
try {
client.getClientSocket().close();
} catch (IOException e) {
// TODO 自动生成 catch 块
//Logger logger = new Logger(System.out);
//logger.log("错误-" + e.toString());
} finally{
clients.removeElement(client);
}
}
public static synchronized void sendClients(StringBuffer sb) {
for(int i=0;i<clients.size();i++){
Client client = (Client) clients.elementAt(i);
client.send(sb);
}
}
public static synchronized void sendClients(StringBuffer sb,String ownerName,String toName) {
for(int i=0;i<clients.size();i++){
Client client = (Client) clients.elementAt(i);
if(toName.equals(client.getClientName()) || toName.equals("所有的人") || ownerName.equals(client.getClientName())){
client.send(sb);
}
}
}
public static synchronized void sendClients(Client ownerClient) {
for(int i=0;i<clients.size();i++){
Client client = (Client) clients.elementAt(i);
if(client.getClientName().equals(ownerClient.getClientName())){
client.send(new StringBuffer("MSG"+CommandDelimiters+"系统信息>欢迎你进入!"));
}else{
client.send(new StringBuffer("MSG"+CommandDelimiters+"系统信息>["+ownerClient.getClientName()+"]用户进入!"));
}
}
}
public static void main(String[] args) {
int port = 8888;
if(args.length>0){
port = Integer.parseInt(args[0]);
}
//Logger logger = new Logger(System.out);
//logger.log("信息-ChatServer["+port+"]服务正在启动...");
try {
server = new ServerSocket(port);
} catch (IOException e) {
// TODO 自动生成 catch 块
//logger.log("错误-"+e.toString());
}
while(true){
if(clients.size()<5){
try {
socket = server.accept();
if(socket != null){
//logger.log("信息-"+socket.toString()+"连接");
}
} catch (IOException e) {
// TODO 自动生成 catch 块
//logger.log("错误-"+e.toString());
}
int i=0;
do{
Client client = new Client(socket);
if(client.getClientName() != null){
clients.addElement(client);
if(checkName(client)){
//logger.log("信息-"+"目前有["+clients.size()+"]个用户已连接");
sendClients(client);
client.start();
notifyRoom();
}else{
client.send(new StringBuffer("TAKEN"));
disconnect(client);
}
i++;
}
break;
}while(i<clients.size());
}else{
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO 自动生成 catch 块
//logger.log("错误-"+e.toString());
}
}
}
}
}
//=======================================;
// Client.java
//=======================================;
/*
* 创建日期2005-10-10
*
* TODO 要更改此生成的文件的模板,请转至
* 窗口-首选项- Java -代码样式-代码模板
*/
package com.klstudio.socket.chat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
//import com.klstudio.util.Logger;
/**
* @author kinglong
*
* TODO 要更改此生成的类型注释的模板,请转至窗口-首选项- Java -代码样式-代码模板
*/
public class Client extends Thread {
private Socket clientSocket;
private String clientName;
private String clientIp;
private BufferedReader br;
private PrintStream ps;
//private Logger logger;
private ChatServer server;
public Client(Socket socket) {
//this.logger = new Logger(System.out);
this.clientSocket = socket;
try {
this.br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
this.ps = new PrintStream(socket.getOutputStream(),true,"utf-8");
String info = this.br.readLine();
if(info!=null){
String[] info_arr = info.split(ChatServer.CommandDelimiters);
if(info_arr.length>1){
this.clientName = info_arr[1];
}
this.clientIp = socket.getRemoteSocketAddress().toString();
}else{
socket.close();
}
} catch (IOException e) {
// TODO 自动生成 catch 块
//this.logger.log("错误-" + e.toString());
}
}
/**
* @return 返回 ip。
*/
public String getClientIp() {
return clientIp;
}
/**
* @return 返回 name。
*/
public String getClientName() {
return clientName;
}
/**
* @return 返回 socket。
*/
public Socket getClientSocket() {
return clientSocket;
}
public void send(StringBuffer msg){
this.ps.println(msg.toString()+"\0");
//this.ps.flush();
}
public void run() {
while (true) {
String line = null;
try {
line = this.br.readLine();
} catch (IOException e) {
// TODO 自动生成 catch 块
//this.logger.log("错误-" + e.toString());
ChatServer.disconnect(this);
ChatServer.notifyRoom();
return;
}
if (line == null) {
//this.logger.log("信息-[" + this.clientName + this.clientIp + "]用户离开!");
ChatServer.disconnect(this);
ChatServer.notifyRoom();
if(this.clientName != null){
ChatServer.sendClients(new StringBuffer("MSG"+ChatServer.CommandDelimiters+"系统信息>[" + this.clientName + "]用户离开!"));
}
return;
}
//this.logger.log("信息-"+line);
String[] cmd_arr = line.split(ChatServer.CommandDelimiters);
String keyword = cmd_arr[0];
keyword = keyword.substring(1);
if(keyword.equals("MSG")){
StringBuffer msg = new StringBuffer("MSG"+ChatServer.CommandDelimiters);
msg.append(this.clientName+">");
msg.append(cmd_arr[1]);
ChatServer.sendClients(msg,this.clientName,cmd_arr[2]);
}else if(keyword.equals("QUIT")){
//this.logger.log("信息-[" + this.clientName + this.clientIp + "]用户离开!");
ChatServer.disconnect(this);
ChatServer.notifyRoom();
ChatServer.sendClients(new StringBuffer("MSG"+ChatServer.CommandDelimiters+"系统信息>[" + this.clientName + "]用户离开!"));
this.stop();
return;
}
}
}
}
作者:
五星上将
时间:
2014-11-26 21:56
//注意,服务端向客户端发送的信息,必需以”\0”,空字符结尾,否则客户端也无法接收到信息!
作者:
duanxb
时间:
2014-11-27 11:56
谢谢楼主提供分享
作者:
zjtp7
时间:
2014-11-27 17:08
学习,感谢楼主提供分享。
作者:
gxj000
时间:
2014-11-27 17:30
支持一下!!
作者:
yipingzi
时间:
2015-1-22 08:56
逛一逛,顶一顶。
欢迎光临 初级视频编辑室|草蜢非编论坛|初级视编室|草蜢视频编辑|会声会影|威力导演|电子相册 (http://shibianshi.com/)
Powered by Discuz! X3.2