`
phantom
  • 浏览: 162710 次
社区版块
存档分类
最新评论
阅读更多

import java.awt.event.*;
import java.util.*;
import java.awt.*;
import java.io.*;
import java.net.*;

/**
 *
 * CommServer
 * <BR><BR>
 * Generic Flash Communication Server.  All communications sent and received
 * are (must be) terminated with a null character ('\0') consistent with
 * the way Flash does socket communications.  Any client which uses this
 * protocol should also work.
 * <BR><BR>
 * The server accepts messages from connected clients and broadcasts (verbatim)
 * those messages to all connected clients.  When clients connect or disconnect
 * the server also broadcasts the number of clients via a NUMCLIENTS tag.
 *
 * Usage: java CommServer [port]
 *
 * @author  Derek Clayton   derek_clayton@iceinc.com
 * @version 1.0.1
 */

public class CommServer {
    private Vector clients = new Vector();  // a list of all connected clients
    ServerSocket server;                    // the server
   
    /**
     * Constructor for the CommServer.  Begins the start server process.
     * @param   port   Port number the server should listen to for connections.
    */
    public CommServer(int port) {
        startServer(port);
    }

    /**
     * Starts the server and listens for connections.
     * @param   port   Port number the server should listen to for connections.
    */
    private void startServer(int port) {
        writeActivity("Attempting to Start Server");
       
        try {
            // --- create a new server
            server = new ServerSocket(port);
            writeActivity("Server Started on Port: " + port);
            // --- while the server is active...
            while(true) {
                // --- ...listen for new client connections
                Socket socket = server.accept();
                CSClient client = new CSClient(this, socket);
                writeActivity(client.getIP() + " connected to the server.");
                // --- add the new client to our client list
                clients.addElement(client);
                // --- start the client thread
                client.start();  
                // --- broadcast the new number of clients
                broadcastMessage("<NUMCLIENTS>" + clients.size()
                               + "</NUMCLIENTS>");
            }
        } catch(IOException ioe) {
            writeActivity("Server Error...Stopping Server");
            // kill this server
            killServer();
        }
    }

    /**
     * Broadcasts a message too all connected clients.  Messages are terminated
     * with a null character.
     * @param   message    The message to broadcast.
    */
    public synchronized void broadcastMessage(String message) {
        // --- add the null character to the message
        message += '\0';
       
        // --- enumerate through the clients and send each the message
        Enumeration enum = clients.elements();
        while (enum.hasMoreElements()) {
            CSClient client = (CSClient)enum.nextElement();
            client.send(message);
        }
      
    }

    /**
     * Removes clients from the client list.
     * @param   client    The CSClient to remove.
    */
    public void removeClient(CSClient client) {
        writeActivity(client.getIP() + " has left the server.");
       
        // --- remove the client from the list
        clients.removeElement(client);
       
        // --- broadcast the new number of clients
        broadcastMessage("<NUMCLIENTS>" + clients.size() + "</NUMCLIENTS>");
    }

    /**
     * Writes a message to System.out.println in the format
     * [mm/dd/yy hh:mm:ss] message.
     * @param   activity    The message.
    */
    public void writeActivity(String activity) {
        // --- get the current date and time
        Calendar cal = Calendar.getInstance();
        activity = "[" + cal.get(Calendar.MONTH)
                 + "/" + cal.get(Calendar.DAY_OF_MONTH)
                 + "/" + cal.get(Calendar.YEAR)
                 + " "
                 + cal.get(Calendar.HOUR_OF_DAY)
                 + ":" + cal.get(Calendar.MINUTE)
                 + ":" + cal.get(Calendar.SECOND)
                 + "] " + activity + "\n";

        // --- display the activity
        System.out.print(activity);
    }

    /**
     * Stops the server.
    */
    private void killServer() {
        try {
            // --- stop the server
            server.close();
            writeActivity("Server Stopped");
        } catch (IOException ioe) {
            writeActivity("Error while stopping Server");
        }
    }
   
    public static void main(String args[]) {
        // --- if correct number of arguments
        if(args.length == 1) {
           
        } else {
        // otherwise give correct usage
            System.out.println("Usage: java CommServer [port]");
        }
       
        CommServer myCS = new CommServer(3000);
    }
}

 

//==================================================================

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// moock chat client
// version 1.0.1
//
// java server by derek clayton
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

// *** general init
var incomingUpdated = false; // trace whether or not we need to scroll to the end of the incoming window
incoming = "";     // clear the HTML text field so it doesn't start with a blank <P> tag

// attach the scroll manager movie (see its child movie's enterframe event for scroll code)
// note that we only need the scroll manager because of text field bugs in r30 of the flash 5 player
attachMovie("processScroll", "processScroll", 0);

var click = new Sound();  // sound to play when user receives a message
click.attachSound("click");

var welcomeSound = new Sound(); // sound to play when user joins or leaves
welcomeSound.attachSound("welcome");

// turn off ugly yellow highlight on buttons
_focusrect = 0;

// *** creates a new socket and attempts to connect to the server
function connect () {
 mySocket = new XMLSocket();
 mySocket.onConnect = handleConnect;
 mySocket.onClose = handleClose;
 mySocket.onXML = handleIncoming;
    // specify your server and port number here
 if (!mySocket.connect("localhost", 3000)) gotoAndStop("connectionFailed");
 mySocket.host = host;
 mySocket.port = port;
}

// *** event handler to respond to the completion of a connection attempt
function handleConnect (succeeded) {
 if(succeeded) {
  mySocket.connected = true;
  gotoAndStop("chat");
  Selection.setFocus("_level0.outgoing");
 } else {
  gotoAndStop("connectionFailed");
  trace("connection failed");
 }
}

// *** event handler called when server kills the connection
function handleClose () {
 incoming += ("the server at " + mySocket.host + " has terminated the connection.\n");
 incomingUpdated = true;
 mySocket.connected = false;
 numClients = 0;
}

// *** event handler to receive and display incoming messages
function handleIncoming (messageObj) {
 
 // display the received xml data in the output window
 trace("--------new data received-----------");
 trace(">>" + messageObj.toString() + "<<");
 trace("-------- end of new data -----------");

 // tell the text field manager it's time to scroll
 incomingUpdated = true;
 lastScrollPos = incoming.scroll;

 // check the time
 var now = new Date();
 var hours = now.getHours();
 var minutes = now.getMinutes();
 var seconds = now.getSeconds();
 hours = (hours < 10 ? "0" : "") + hours;
 minutes = (minutes < 10 ? "0" : "") + minutes;
 seconds = (seconds < 10 ? "0" : "") + seconds;

 // the server sends NUMCLIENTS any time a client connects or disconnects.
 // if we find NUMCLIENTS in the xml object...
 if (messageObj.firstChild.nodeName == "NUMCLIENTS") {
  // ...then check if the incoming messages window is empty. if it is...
  if(incoming == "") {
   // ...then the user is new, so welcome them
   incoming += ("<FONT COLOR='#507373'><B>welcome to moock comm 1.0.1, " 
    + convertTags(userID) + "\n"
    + "   Connection time:</B> " + hours + ":" + minutes + ":" + seconds + "\n"
    + "<B>   server:</B> 京华时报 Flash XmlSocket Chat Server</FONT>\n\n");
  } else {
   // otherwise, someone has arrived or departed, so tell the user
   if(parseInt(messageObj.firstChild.firstChild.nodeValue) > numClients) {
    // report the client arrival in the chat window
    incoming += ("<FONT COLOR='#507373'><B>" + hours + ":" + minutes + ":"
                + seconds + " a new user has connected."  + "</B></FONT>\n");
    } else {
    // report the client departure in the chat window
    incoming += ("<FONT COLOR='#507373'><B>" + hours + ":" + minutes + ":"
                + seconds + " a user disconnected."  + "</B></FONT>\n");  
   }
  }
  // finally, keep track of the number of clients and play a welcome sound
  numClients = messageObj.firstChild.firstChild.nodeValue;
  welcomeSound.setVolume(100);
  welcomeSound.start();
 } else {
  // no NUMCLIENTS node was found, so this is just a regular message.
  // grab the user name and message from our xml object
  var user = messageObj.firstChild.firstChild.nodeValue;
  var message = messageObj.childNodes[1].firstChild.nodeValue;

  // add the message to the chat window, with a time stamp
  incoming += (hours + ":" + minutes + ":"
    + seconds + "<B>" + unescape(user) + "</B>&gt;&gt; " + addLinks(unescape(message)) + "\n");

  // now do the new message click. if it's been more than 30 secs since the last message,
  // sound a loud click. otherwise sound a quiet click
  trace("time since last message: " + (now - lastIncomingMessageTime));
  if (lastIncomingMessageTime && now - lastIncomingMessageTime > 30000) {
   click.setVolume(200);
  } else {
   click.setVolume(30);
  }
  click.start();
  }

 // truncate the contents of the incoming messages window if it's longer than 5000 characters
 if(incoming.length > 5000) {
  var nearestNewline = incoming.indexOf("\n", incoming.length - 5000);
  incoming = incoming.substring(nearestNewline, incoming.length);
 }

 // remember when this message arrived for next time
 lastIncomingMessageTime = now;
}

// *** sends a new xml object to the server
function sendMessage() {
 // create the message to send as an xml source fragment. we're sending html so we
 // have to escape our text and change < and > to entities via convertTags
 var message = '<USER>%20' + escape(convertTags(userID)) + '</USER><MESSAGE>'
  + escape(convertTags(outgoing)) + '%20</MESSAGE>'; // note that the forced spaces (%20) are required so
               // MESSAGE and USER always have a text child node
 
 // convert the message into an xml object hierarchy
 messageObj = new XML();
 messageObj.parseXML(message);

 // check what we're sending
 trace("Sending: " + messageObj);

 // if a socket object has been created and is connected, send the xml message
 // otherwise warn the user that they need to connect
 if (mySocket && mySocket.connected) {
  mySocket.send(messageObj);
  outgoing = "";
 } else {
  // the server must have kicked us off...
  incoming += "<FONT COLOR='#507373'><B>you are no longer connected. please reconnect."
   + "</B></FONT>\n";
  incomingUpdated = true;
 }
}

// *** closes the connection to the server
function quit() {
 if (mySocket.connected) {
  mySocket.close();
  mySocket.connected = false;
  numClients = 0;
  incoming = "";
  gotoAndStop("login");
 }
}


// *** changes < and > to &lt; and &gt;
function convertTags(theString) {
 var tempString = "";
 for(var i = 0; i < theString.length; i++) {
  if(theString.charAt(i) == "<") {
   tempString += "&lt;";
  } else if (theString.charAt(i) == ">") {
   tempString += "&gt;";
  } else {
   tempString += theString.charAt(i);
  }
 }
 trace("tempString: " + tempString);
 return tempString;
}

// *** inserts <A> tags into a string anywhere a "www" occurs
function addLinks (theString) {
 var startIndex = 0;
 var tempString = "";
 var linkString;
 var URL;
 var beginURL;
 var endURL;
 if(theString.indexOf("www") != -1) {
  while(theString.indexOf("www", startIndex) != -1) {
   tempString += theString.substring(startIndex, theString.indexOf("www", startIndex));
   beginURL = theString.indexOf("www", startIndex);
   endURL = (theString.indexOf(" ", beginURL) != -1) ? theString.indexOf(" ", beginURL) : theString.length;
   URL = theString.substring(beginURL, endURL);
   linkString = "<A HREF='http://" + URL + "' TARGET='_blank'><U><FONT COLOR='#FFFFCC'>" + URL + "</FONT></U></A>"; 
   tempString += linkString;
   startIndex = endURL;
  }
  tempString += theString.substring(endURL, theString.length);
  return tempString;
 } else {
  return theString;
 }
}

 

 

 

 

 


 

 


 

分享到:
评论

相关推荐

    基于java的开发源码-Flash解析、生成器 jActionScript.zip

    基于java的开发源码-Flash解析、生成器 jActionScript.zip 基于java的开发源码-Flash解析、生成器 jActionScript.zip 基于java的开发源码-Flash解析、生成器 jActionScript.zip 基于java的开发源码-Flash解析、生成...

    java开发环境建立--FLASH演示

    java开发环境建立--FLASH演示.swf版,简单明了

    avengereug-java-backend-develop_flash源码_

    【标题】"avengereug-java-backend-develop_flash源码_" 提供的是一个关于Java后端开发的项目,其中包含了与Flash相关的源代码。这个项目的重点是利用shell脚本来实现便捷的开发流程,包括项目的启动、停止、更新...

    Java-Flash Bridge-开源

    JavaFlashBridge 使用 JDic 和 JavaScript 以及 Flash 集成工具包在 Java Panel 容器中提供 Flash 播放器的集成。 通信协议是基于字符串的,所以它可以是 XML、序列化对象或其他任何东西。 它是事件驱动的。

    java-flashcards

    Java抽认卡 目录 基本信息 这个项目是一个简单的抽认卡应用程序。 技术领域 使用以下项目创建项目: Java v 11 Spring Boot v 2.4.3(DATA,WEB,VALIDATION,DEVTOOLS) PostgreSQL 设置 要运行此项目,请使用...

    java与flash通信.pdf

    在深入讨论Java与Flash的通信技术之前,我们需要了解几个关键概念。首先,Java是一种广泛使用的编程语言,它支持面向对象编程,并提供跨平台能力。而Flash是一种由Adobe Systems开发的多媒体技术,主要用于创建动画...

    open-flash-chart

    "Open-Flash-Chart"是一个强大的图表生成库,专门用于创建高质量、交互式的Flash图表。这个工具被设计成跨平台的,支持多种编程语言,包括JAVA和.NET,使得开发人员能够在他们的应用程序中轻松地集成数据可视化功能...

    整合Flex和Java--配置篇

    Flex通常使用ActionScript编程语言,并基于Adobe Flash Player或Adobe AIR运行时环境来展示内容。Java则通过JVM(Java虚拟机)运行,可以提供服务器端的服务和数据处理。两者之间的通信通常通过HTTP或AMF(Action ...

    fckeditor-java-demo-2.6 修改

    对fckeditor 文件上传功能的修改 1.文件上传绝对路径配置 2.文件上传按上传日期保存 3.浏览上传图片文件和flash文件添加预览功能

    flex与java--Blazeds学习(配置)

    ### Flex与Java—Blazeds学习(配置) #### 一、环境搭建 ##### 1. 安装JDK 为了确保整个开发环境的兼容性和稳定性,我们首先需要安装JDK (Java Development Kit)。JDK 的安装过程相对简单,只需要遵循安装向导的...

    maven-flash-plugin-0.1.jar

    maven-flash-plugin-0.1.jar

    计算机毕业课程设计-[其他类别]JS+Flash让网页元素发光的插件 glow! 0.1_glow.zip

    Java-JSP计算机毕业设计课程设计项目源码 Java-JSP计算机毕业设计课程设计项目源码 Java-JSP计算机毕业设计课程设计项目源码 Java-JSP计算机毕业设计课程设计项目源码 Java-JSP计算机毕业设计课程设计项目源码 Java-...

    java-flex-mysql

    开发者可以利用Flex Builder或者Flash Builder这样的IDE来编写Flex代码,构建组件化的UI。Flex应用程序通过AMF(Action Message Format)与Java后端进行通信,这是一种高效的数据交换格式,能快速传输列表数据。 **...

    基于Java的源码-Flash解析、生成器 jActionScript.zip

    【标题】"基于Java的源码-Flash解析、生成器 jActionScript.zip"涉及的核心知识点是Java编程语言在处理Flash内容上的应用,具体是Flash ActionScript的解析与生成。ActionScript是Adobe Flash平台上的一种脚本语言,...

    Open-Flash-Chart手册chm格式文档压缩包

    Open-Flash-Chart(简称OFC)是一个开源的Flash图表绘制工具,它提供了丰富的图表类型和强大的配置选项,使得数据可视化变得简单而直观。Open-Flash-Chart免费开源,用户可以自由使用、修改和分发其源代码。它基于...

    java + flash 上传

    Java和Flash组合提供了一种在浏览器环境中实现文件上传的有效方式。本篇文章将详细探讨如何使用Java后端和Flash前端来实现多文件选择和配置上传文件名及大小的上传功能。 首先,我们需要理解Java和Flash在文件上传...

    [影音娱乐]JSP版Flash小游戏小偷_jsgame.zip

    Java-JSP计算机毕业设计课程设计项目源码 Java-JSP计算机毕业设计课程设计项目源码 Java-JSP计算机毕业设计课程设计项目源码 Java-JSP计算机毕业设计课程设计项目源码 Java-JSP计算机毕业设计课程设计项目源码 Java-...

    flexjava-sockete.rar

    - FlexJava可能是一个自定义的框架,或者是指使用Flex技术(ActionScript和Flash Builder)与Java后台进行交互的应用。 4. **创建Socket连接** - 服务器端使用`ServerSocket server = new ServerSocket(port)`...

    java-flex-webroot配置文件和JAVA包

    对于Flex应用来说,它通过Adobe的Flash Player或Adobe AIR运行在客户端,与服务器进行通信通常采用AMF(Action Message Format)协议,这是一种高效的数据交换格式。在Java端,我们可以使用BlazeDS或LCDS(LiveCycle...

    Flex-Java-file-upload.zip_flex

    在Flex中,文件上传可以通过Flash Player的FileReference类来实现。这个类允许用户选择本地文件,并将其上传到指定的URL。在选择文件后,FileReference对象可以调用upload()方法,将文件作为POST请求的一部分发送到...

Global site tag (gtag.js) - Google Analytics