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

📄 chatclient.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.examples.chatsystem;import java.awt.BorderLayout;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.JTextField;import net.sf.cscc.ClientConnectionManager;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;/** *  This class represents the client in a client/server-chatsystem. The Chatsystem is a small application *  intended to demonstrate the usage of this client/server communication component. The Client has to *  connect to a {@link net.sf.cscc.examples.chatsystem.ChatServer} to participate a session. The client sends data to *  the server by calling the method {@link net.sf.cscc.ClientConnectionManager#sendDataEvent(DataEvent de)} *  and receives data from the server by calls of the method {@link #receiveEvent(DataEvent de)}. *  The method {@link #receiveEvent(CommunicationEvent ce)} allows the client to receive informations *  about the status of the connection. * *	@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 *						2006-11-28 SM Comments revised. *	@version			$Date: 2007/07/01 17:04:07 $, $Author: reode_orm $, $Revision: 1.1 $ */public class ChatClient extends JFrame implements ActionListener, DataEventReceivingObserver, CommunicationEventObserver {	/**	 *  Client connection manager, handles the connection to the server.	 */	private ClientConnectionManager clientConnectionManager;	/**	 *  Status of the connection (connected or not connected).	 */	private boolean connected = false;	/**	 *  TCP port of the connection.	 */	private int port = 2700;	/**	 *  Name to appear in the chat session.	 */	public String nickname;	/**	 *  TextField for DNS name or IP address of the server.	 */	private JTextField serverField;	/**	 *  Textfield for entering the name to appear in the chat session.	 */	private JTextField nicknameField;	/**	 *  Button to connect to the server.	 */	private JButton connectButton;	/**	 *  TextArea to dispplay the messages of the chat session.	 */	private JTextArea messageArea;	/**	 *  TextField for entering a message to send.	 */	private JTextField messageField;	/**	 *  Button to send the message.	 */	private JButton sendButton;	/**	 *  Constructor to initialize the Client.	 *  @pre	true	 *  @post	clientConnectionManager != null	 */	public ChatClient() {		super("Chat Client");		// Initialize a new connectionManager for the given port		clientConnectionManager = new ClientConnectionManager(port);		// Register the client as observer for DataEvents and CommunicationEvents		// Casts are necassary because the two methods have the same name		clientConnectionManager.addObserver((CommunicationEventObserver)this);		clientConnectionManager.addObserver((DataEventReceivingObserver)this);		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() {		setSize(550, 450);		getContentPane().setLayout(new BorderLayout());		JPanel connectionPanel = new JPanel();		connectionPanel.setLayout(new GridLayout(1, 5));		connectionPanel.add(new JLabel(" Nickname: "));		nicknameField = new JTextField();		connectionPanel.add(nicknameField);		connectionPanel.add(new JLabel(" Server: "));		serverField = new JTextField("localhost");		connectionPanel.add(serverField);		connectButton = new JButton("connect");		connectButton.addActionListener(this);		connectionPanel.add(connectButton);		messageArea = new JTextArea();		messageArea.setEditable(false);		JPanel messagePanel = new JPanel();		messagePanel.setLayout(new BorderLayout());		messagePanel.add(new JLabel(" Message: "), BorderLayout.WEST);		messageField = new JTextField();		messageField.addActionListener(this);		messagePanel.add(messageField, BorderLayout.CENTER);		sendButton = new JButton("send message");		sendButton.addActionListener(this);		messagePanel.add(sendButton, BorderLayout.EAST);		getContentPane().add(connectionPanel, BorderLayout.NORTH);		getContentPane().add(new JScrollPane(messageArea), BorderLayout.CENTER);		getContentPane().add(messagePanel, BorderLayout.SOUTH);	}	/**	 *   This method handles button pressed events, 	 *   ie. <i>Connect/Disconnect</i> and <i>send message</i>.	 *   @pre	event != null	 *   @post	true	 *   @param	event ActionEvent object describing which kind of event 	 *          occurred in the gui.	 */	public void actionPerformed(ActionEvent event) {		if(event.getSource() == connectButton && !connected) {			nickname = nicknameField.getText();			if(nickname.equals("")) {				messageArea.append("Please enter a nickname!\n");			} else {				clientConnectionManager.open(serverField.getText());			}		}		else if(event.getSource() == connectButton && connected) {			clientConnectionManager.close();		}		else if((event.getSource() == sendButton || event.getSource() == messageField) && connected) {			// Get Message, concatenate with nickname and send this String to the server			if(!messageField.getText().equals("")) {				String message = nickname + ": " + messageField.getText() + "\n";				DataEvent de = new DataEvent(new Integer(1), message);				clientConnectionManager.sendDataEvent(de);				messageField.setText("");			}		}	}	/**	 *   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) {		// Show received messages in the messageArea		messageArea.append(de.getData().toString());	}	/**	 *   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):				messageArea.append("ChatServer: Connection established!\n");				connected = true;				connectButton.setText("disconnect");				break;			case (CommunicationEvent.CONNECTION_BROKEN):                		messageArea.append("ChatServer: Connection closed!\n");				connected = false;				connectButton.setText("connect");                		break;			case (CommunicationEvent.CONNECTION_CLOSED):                		messageArea.append("ChatServer: Connection closed!\n");				connected = false;				connectButton.setText("connect");                		break;		}	}	/**	 *   Method to terminate the application.	 *   	 *   @pre	true	 *   @post	true	 */	public void exit() {		clientConnectionManager.close();		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 ChatClient().setVisible(true);	}}

⌨️ 快捷键说明

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