📄 chatserver.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.examples.chatsystem;import java.awt.BorderLayout;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.net.InetAddress;import java.net.UnknownHostException;import javax.swing.JFrame;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.JTextField;import net.sf.cscc.CommunicationEvent;import net.sf.cscc.CommunicationEventObserver;import net.sf.cscc.DataEvent;import net.sf.cscc.DataEventBaseObserver;import net.sf.cscc.DataEventReceivingObserver;import net.sf.cscc.ServerConnectionManager;/** * This class represents the server in the chatsystem. * The Chatsystem is a small application * intended to demonstrate the usage of this client/server * communication component. The server manages * the connections from multiple * {@link net.sf.cscc.examples.chatsystem.ChatClient} on a specific port. It sends data * (messages in the chat session) received from one client to all other * clients by calling the method * {@link net.sf.cscc.ServerConnectionManager#sendBroadCastEvent(DataEvent de)}. * Receiving data or informations about the status of the connection * is done by the methods {@link #receiveEvent(DataEvent de)} and * {@link #receiveEvent(CommunicationEvent ce)}.<br> * * The server is just an example to show the usage of the * communication component. It doesn't i.e. check * if the nickname is already used by another client. Instead it * allows multiple clients to use the same * nickname without any authentication * * @author Tobias Reinhard (TR) * @copyright Silvio Meier, Tobias Reinhard, 2003 * @history 2003-05-18 TR First version * 2003-05-20 TR Reference in comment corrected * 2004-12-13 SM Some cleaning of unused things. * 2006-11-28 SM Comments revised. * @version $Date: 2007/07/01 17:04:07 $, $Author: reode_orm $, $Revision: 1.1 $ */public class ChatServer extends JFrame implements DataEventReceivingObserver, CommunicationEventObserver { /** * IP adress of the server. */ private InetAddress serverAddress; /** * Specifies the TCP port to listen for connections. */ private int portNumber = 2700; /** * The server connection manager which handles the * communication with the clients. */ private ServerConnectionManager serverConnectionManager; /** * TextField to show the address of the server. */ private JTextField serverBar; /** * TextArea to dispplay the messages of the chat session. */ private JTextArea messageArea; /** * TextField to show status informations about the connections. */ private JTextField statusBar; /** * Constructor to initialize the Server. * * @pre true * @post serverConnectionManager != null */ public ChatServer() { super("Chat server"); setSize(400, 400); // Initialize a new ConnectionManager for the given port serverConnectionManager = new ServerConnectionManager(portNumber); // Register the server as observer for DataEvents and CommunicationEvents // Casts are necassary because the two methods have the same name serverConnectionManager.addObserver((CommunicationEventObserver)this); serverConnectionManager.addObserver((DataEventReceivingObserver)this); // Wait for connections from the clients serverConnectionManager.beginListening(); // Get the IP address of the server try { serverAddress = InetAddress.getLocalHost(); } catch(UnknownHostException e) {} initGUI(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { exit(); } }); } /** * This method initializes the gui of the client. * * @pre true * @post true */ private void initGUI() { getContentPane().setLayout(new BorderLayout()); serverBar = new JTextField("Server running at address " + serverAddress); serverBar.setEditable(false); messageArea = new JTextArea(); messageArea.setEditable(false); statusBar = new JTextField(); statusBar.setEditable(false); getContentPane().add(serverBar, BorderLayout.NORTH); getContentPane().add(new JScrollPane(messageArea), BorderLayout.CENTER); getContentPane().add(statusBar, BorderLayout.SOUTH); } /** * This interface method is called by the communication component. The implenting class has to * register at the specific object of the class * {@link net.sf.cscc.ClientConnectionManager#addObserver(DataEventBaseObserver debo)} * to get notifications about new data events in the event queue. The data is given as argument. * * @pre de != null * @post true * @param de DataEvent object, encapsulating the transmitted data. * @see net.sf.cscc.DataEventObserver#receiveEvent() */ public void receiveEvent(DataEvent de) { // send received message to all clients (including the sender of the message) messageArea.append(de.getData().toString()); serverConnectionManager.sendBroadCastEvent(de); } /** * This interface method is called by communication component class, * every time a communication event occurred. The implenting class has * to register at the specific object of the class * {@link net.sf.cscc.ClientConnectionManager#addObserver(DataEventBaseObserver debo)} * to get notifications about new communication events in the event queue. * This is done by calling the method * {@link net.sf.cscc.ServerConnectionManager#addObserver(CommunicationEventObserver o)} * for observing the communication events of the server, respectively * the method {@link net.sf.cscc.ClientConnectionManager#addObserver(CommunicationEventObserver o)} * for the communication events of the client. * * @pre ce != null * @post true * @param ce CommunicationEvent which is delivered to the implementor of * this interface (ie. the observer). */ public void receiveEvent(CommunicationEvent ce) { switch(ce.getEventId()) { case(CommunicationEvent.CONNECTION_ESTABLISHED): statusBar.setText(ce.getData() + " connected to server!\n"); break; case(CommunicationEvent.CONNECTION_BROKEN): statusBar.setText("Connection to " + ce.getData() + " broken!\n"); break; case(CommunicationEvent.CONNECTION_CLOSED): statusBar.setText(ce.getData() + "disconnected from server!"); break; } } /** * Method to terminate the application. * * @pre true * @post true */ public void exit() { serverConnectionManager.closeAllConnections(); System.exit(0); } /** * This method starts up the client. * * @pre true * @post ChatClient != null * @param args the command line arguments */ public static void main(String[] args) { new ChatServer().setVisible(true); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -