⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 objectsender.java

📁 自己写的一个聊天的小程序 请多多指教
💻 JAVA
字号:
/* * Copyright (c) 2003 - 2007, Silvio Meier and Tobias Reinhard * * All rights reserved. *  * Redistribution and use in source and binary forms,  * with or without modification, are permitted provided  * that the following conditions are met: * *   o Redistributions of source code must retain the above  *     copyright notice, this list of conditions and the  *     following disclaimer. *   o Redistributions in binary form must reproduce the above  *     copyright notice, this list of conditions and the  *     following disclaimer in the documentation and/or other  *     materials provided with the distribution. *   o The names of its contributors may not be used to endorse  *     or promote products derived from this software without  *     specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */package net.sf.cscc;import java.io.IOException;import java.io.InvalidClassException;import java.io.NotSerializableException;import java.io.ObjectOutputStream;import java.net.Socket;/** *   This class implements a threading routine, waiting *   for outgoing data events. If data events are sent, they are *   internally first put into a event queue, then they *   are processed by the sender thread and sent to the communication partner. * *   @author            Silvio Meier (SM) *   @copyright      	Silvio Meier, Tobias Reinhard, 2003 *   @history			2003-05-09 SM First Version *                      2003-05-14 SM working on additional methods and events, *                      correction of some comments. *                      2003-05-20 TR Comments corrected *                      2003-06-12 SM Now receiver thread handles serialization exceptions *                      by throwing an exception. *                      2003-06-13 SM Now the object input stream is reset each time after *                      receiving an object. Otherwise this can cause a OutOfMemoryError. *                      2003-06-14 SM some small changes in the run() method. *                      2003-06-16 SM Removed some debugging output. *                      2003-06-24 SM Now better exception handling. * 						2004-12-13 SM Some cleaning of unused things. * 						2006-11-28 SM Revised comments. *   @version		$Date: 2007/07/01 17:04:05 $, $Author: reode_orm $, $Revision: 1.1 $ * */class ObjectSender extends Thread {    /**     * Refers to the event queue for the out going messages      * (messages that have to be sent to the communication partner).     */    private Queue outGoingMessages;    /**     *  The object output stream serializes the data events (messages) sent over     *  the network.     */    private ObjectOutputStream out = null;    /**     *	If true, the connections is open. If the connection is     *  not open, the corresponding thread is not executing the {@link #run()}     *  method.     */    private boolean connected;    /**     *  The owning communication implements a callback interface for the     *  sake of decoupling.     */    private CommunicationController controller;    /**     *   Intializes this client connection object using the given      *   outgoing event queue.     *        *   @pre s != null && controller != null     *   @post connected == false     *   @param s Socket object representing the connection between client     *          and server.     *   @param controller Controller of the communication     *   @throws net.sf.cscc.CsccException if object sender thread could not be instantiated     */    public ObjectSender(Socket s, CommunicationController controller) {        // indicates if connection is active        connected = false;        this.controller = controller;        this.setPriority(Thread.MAX_PRIORITY);        // queue for sent events        outGoingMessages = new Queue();        try{            // creates new input and output stream for the client            out = new ObjectOutputStream(s.getOutputStream());        }        catch (Exception e) {            throw new CsccException(e.getMessage());        }        connected = true;        start();    }    /**     *   This method closes the connection to the communication partner.     *   After calling this method, this object can not be used any more.     *     *   @pre true     *   @post connected == false     *   @throws net.sf.cscc.CsccException if the object sender could      *           not be closed.     */    public  void close() {        if (!connected) {            connected = false;            try {                // close object output stream                // but before write all the content which is currently not written to                // the communication partner                out.flush();                out.close();                out = null;            }            catch (IOException e) {                throw new CsccException(e.getMessage());            }        }    }    /**     *   Enqueues a new DataEvent object at the end of the outgoing event queue.     *        *   @pre de != null     *   @post (dataEvents.size())@pre == (dataEvents.size())@post + 1     *   @param de DataEvent object which is enqued at the end of the queue.     */    public void enqueueDataEvent(DataEvent de) {        // use the synchronization, ie. otherwise different threads may interfere        synchronized (outGoingMessages) {            // enqueue message            outGoingMessages.enqueueDataEvent(de);            // wake up sender thread!            outGoingMessages.notifyAll();        }    }    /**     *   This method runs the communication between two communication partners.     *   Every event object in the outgoing queue is serialized and sent to     *   the communication partner.     *        *   @pre true     *   @post connected == false     *   @throws net.sf.cscc.CsccException if an error occurs during sending     *           then, the thread is stopped.     */    public  void run() {        connected = true;        Object o = null;        // run until the client connection dies.        try {            synchronized(outGoingMessages){                while (connected) {                    // look in the outgoing queue, if there are messages                    // to transmit to the client                    while (outGoingMessages.hasDataEvents()) {                        o = outGoingMessages.dequeueDataEvent();                        out.writeObject(o);                        out.flush();                        out.reset();                    }                    // wait until the notification about                    // an outgoing message is got --> blocked state of thread                    outGoingMessages.wait();                }            }        } catch (InterruptedException ex) {            // do nothing        }        catch (IOException ex) {            // if connection was canceled by the other side -->            // communication event: broken connection            if (connected) {                connected = false;                controller.communicationBroken(this);            }            // if an error occurred during serialization -->            // rethrow a new Exception describing the problem            if ((ex instanceof NotSerializableException) ||            (ex instanceof InvalidClassException)) {                throw new CsccException("Class is not serializable or caused an "+                "exception during serialization!");            } else {            }        }    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -