|
|
|||||||||
|
|||||||||
|
|||||||||
| |
|||
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
I wrote a simple console based chat server and client that worked. It used separate consoles for sending and receiving for each user. This weekend I added a simple UI to the client to put both sender and receiver components in one ui window. It was my first swing ui so I dont really know what Im doing. I basically followed the TextDemo on the sun tutorial site on swing.
Anyway, the client ui wont display when I run it. The questions are: 1. how can I display the ui 2. is this the right way to go about this at all? Here's the client code... Code:
import java.net.*;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ChatClient
extends JPanel implements ActionListener
{
ChatClient_Send m_sender;
ChatClient_Recv m_receiver;
JTextField m_sendField;
JTextArea m_recvArea;
public static void main(String[] args) {
if( args.length == 0 )
{
System.out.println("Usage: ChatClient <client name> <optional server name>\n");
return;
}
final ChatClient newClient = new ChatClient( );
newClient.initCommunications( args );
//Schedule the event-dispatcher to show the UI.
javax.swing.SwingUtilities.invokeLater(
new Runnable()
{
public void run()
{
showUI( newClient );
}
});
}
public ChatClient( )
{
super(new GridBagLayout());
//Create the rest of the widgets
m_sendField = new JTextField(80);
m_sendField.addActionListener(this);
m_recvArea = new JTextArea(10,80);
m_recvArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(m_recvArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//Add Components to this panel.
GridBagConstraints gridbag = new GridBagConstraints();
gridbag.gridwidth = GridBagConstraints.REMAINDER;
gridbag.fill = GridBagConstraints.HORIZONTAL;
add(m_sendField, gridbag);
gridbag.fill = GridBagConstraints.BOTH;
gridbag.weightx = 1.0;
gridbag.weighty = 1.0;
add(scrollPane, gridbag);
}
private void initCommunications( String[] args )
{
// init the sender and reciever
m_sender = new ChatClient_Send( args );
m_receiver = new ChatClient_Recv( args, m_recvArea );
}
public void actionPerformed(ActionEvent evt) {
// Send the text to the server
String line = m_sendField.getText();
m_sender.sendLine( line );
// Select for overwriting
m_sendField.selectAll();
// Scroll to new text
m_recvArea.setCaretPosition(m_recvArea.getDocument ().getLength());
// TODO - respond to =quit
}
private static void showUI( ChatClient newClient ) {
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("Chat Client");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);
//Create the content pane.
JComponent contentPane = newClient;
contentPane.setOpaque(true);
frame.setContentPane(contentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
protected void finalize()
{
m_sender = null;
m_receiver = null;
}
}
class ChatClient_Send
{
Socket m_socket;
String m_whoami;
BufferedWriter m_outToServer;
public ChatClient_Send( String args[] )
{
try
{
// Open the socket =====================
if( args.length < 2 )
m_socket = new Socket(InetAddress.getLocalHost(), 666);
else
m_socket = new Socket(args[1], 666);
m_outToServer = new BufferedWriter(new OutputStreamWriter(m_socket.getOutputStream()));
// Identify myself =====================
m_whoami = args[0];
m_outToServer.write(m_whoami); m_outToServer.newLine();
m_outToServer.write("speaker"); m_outToServer.newLine();
m_outToServer.flush();
}
catch( Exception e )
{
//TODO
}
}
public void sendLine( String line )
{
try
{
m_outToServer.write( line, 0, line.length() );
m_outToServer.newLine();
m_outToServer.flush();
}
catch( Exception e )
{
//TODO
}
}
protected void finalize()
{
try
{
m_outToServer.close();
m_socket.close();
m_socket = null;
}
catch( Exception e )
{
//TODO
}
}
}
class ChatClient_Recv
{
Socket m_socket;
String m_whoami;
BufferedWriter m_outToServer;
BufferedReader m_inFromServer;
public ChatClient_Recv ( String args[], JTextArea textArea )
{
try
{
// Open the socket =========================
if (args.length < 2 )
m_socket = new Socket(InetAddress.getLocalHost(), 666);
else
m_socket = new Socket(args[1], 666);
m_outToServer = new BufferedWriter(new OutputStreamWriter(m_socket.getOutputStream()));
m_inFromServer = new BufferedReader(new InputStreamReader(m_socket.getInputStream()));
// Identify myself =========================
if( args.length == 0 )
{
Date date = new Date();
Random rand = new Random( date.getTime() );
byte bytes[] = new byte[16];
rand.nextBytes(bytes);
m_whoami = bytes.toString();
date = null;
rand = null;
bytes = null;
}
else
m_whoami = args[0];
m_outToServer.write( m_whoami ); m_outToServer.newLine();
m_outToServer.write("listener"); m_outToServer.newLine();
m_outToServer.flush();
// Read from the server ====================
for (String line = m_inFromServer.readLine();
!line.equals("=quit");
line = m_inFromServer.readLine())
{
textArea.append(line + "\n");
}
}
catch ( Exception e ) {
textArea.append("Error: " + e);
}
}
protected void finalize()
{
try
{
m_inFromServer.close();
m_outToServer.close();
m_socket.close();
m_socket = null;
}
catch ( Exception e ) {
//TODO
}
}
}
Thanks!! Last edited by Xylenz : August 2nd, 2004 at 05:08 PM. Reason: no exception |
|
#2
|
|||
|
|||
|
Strangely enough, I do get the UI to display but only when the server is not running. Any idea why?
Heres the server code... Code:
import java.net.*;
import java.io.*;
import java.util.*;
class ChatServer
{
public static void main( String args[] )
{
ServerSocket socket = null;
try
{
socket = new ServerSocket(666);
while( true )
{
// Block until a connection is made then create a thread to handle it
ChatServerThread thread = new ChatServerThread( socket.accept() );
}
}
catch( SecurityException e )
{
System.out.println("Security Exception: " + e );
}
catch( Exception e )
{
System.out.println("Exception: " + e );
}
finally
{
try
{
if(socket != null)
socket.close();
}
catch( Exception e )
{
System.out.println("Exception closing socket: " + e );
}
}
}
}
class ChatServerThread implements Runnable
{
Socket m_socket;
BufferedWriter m_outToClient;
BufferedReader m_inFromClient;
String m_name;
String m_type;
// static map of listeners
static Hashtable sm_listeners = new Hashtable();
ChatServerThread( Socket socket )
{
try
{
m_socket = socket;
Thread m_thread = new Thread( this );
m_thread.start();
}
catch( IllegalThreadStateException e )
{
// should never happen
System.out.println("Thread already started: " + e );
}
catch( Exception e )
{
// should never happen
System.out.println("Error creating client thread: " + e );
}
}
public void run()
{
try
{
// Open the IO buffers ======================
m_outToClient = new BufferedWriter( new OutputStreamWriter(m_socket.getOutputStream()));
m_inFromClient = new BufferedReader( new InputStreamReader(m_socket.getInputStream()));
// Identify the client ======================
m_name = m_inFromClient.readLine();
m_type = m_inFromClient.readLine();
// Handle a listener ========================
if( m_type.equals("listener") )
{
sm_listeners.put( m_name, m_outToClient );
while( true )
Thread.sleep(10);
}
// Handle a speaker ========================
else if( m_type.equals("speaker") )
{
broadcast( "=== " + m_name + " joined ===" );
while( true )
{
String line = m_inFromClient.readLine();
if( (line.charAt(0) == '=') )
{
if( control( line ) )
break; // quit
}
else
broadcast( m_name + " says: " + line );
Thread.sleep(10);
}
}
else
System.out.println("Error! invalid client type: " + m_type );
}
catch( Exception e )
{
System.out.println( m_type + " client exception: " + e);
}
}
protected void broadcast( String message )
{
try
{
// Echo to the server
System.out.println( message );
// Send message to all listeners
Enumeration enum = sm_listeners.elements();
while( enum.hasMoreElements() )
{
BufferedWriter listener =(BufferedWriter) enum.nextElement();
listener.write( message);
listener.newLine();
listener.flush();
}
}
catch( Exception e )
{
System.out.println("Broadcast exception: " + e);
}
}
protected boolean control( String line )
{
try
{
boolean isQuitting = false;
BufferedWriter listener = ((BufferedWriter) sm_listeners.get( m_name ));
if( line.compareToIgnoreCase("=quit") == 0 ||
line.compareToIgnoreCase("=q") == 0 )
{
// Tell the listener to quit
listener.write("=quit");
listener.newLine();
listener.flush();
// Remove me from the list of listeners
sm_listeners.remove( m_name );
// Tell everyone I've left
broadcast( "=== " + m_name + " left ===" );
isQuitting = true;
}
else if( line.compareToIgnoreCase("=list") == 0 ||
line.compareToIgnoreCase("=l") == 0 )
{
Enumeration keys = sm_listeners.keys();
for( int index = 1; keys.hasMoreElements(); index++)
{
listener.write( "=== User: " + keys.nextElement() + " ===");
listener.newLine();
}
}
else if( line.compareToIgnoreCase("=whoami") == 0 ||
line.compareToIgnoreCase("=who") == 0 ||
line.compareToIgnoreCase("=w") == 0 )
{
listener.write("=== I am " + m_name + " ===");
listener.newLine();
}
else if( isTell( line ) )
{
doTell( line );
}
else if( line.compareToIgnoreCase("=help") == 0 ||
line.compareToIgnoreCase("=h") == 0 )
{
listener.write("=== All commands begin with a '=' ==="); listener.newLine();
listener.write("=== Commands may be abbreviated with their first letter. ==="); listener.newLine();
listener.write("=== =Quit - exits ==="); listener.newLine();
listener.write("=== =List - who is listening ==="); listener.newLine();
listener.write("=== =Whoami - my user name ==="); listener.newLine();
listener.write("=== =Tell=user= message - send message to user ==="); listener.newLine();
listener.write("=== =Help - this message ==="); listener.newLine();
}
else
{
listener.write("=== Invalid Command ===");
listener.newLine();
}
listener.flush();
return isQuitting;
}
catch( Exception e )
{
System.out.println("Control error: " + e );
return false;
}
}
protected boolean isTell( String line )
{
StringTokenizer tokenizer = new StringTokenizer( line, "=" );
String tell = tokenizer.nextToken();
tokenizer = null;
if( tell.compareToIgnoreCase("tell") == 0 ||
tell.compareToIgnoreCase("t") == 0 )
return true;
else
return false;
}
protected void doTell( String line )
{
try
{
StringTokenizer tokenizer = new StringTokenizer( line, "=" );
BufferedWriter listener = ((BufferedWriter) sm_listeners.get( m_name ));
if( tokenizer.countTokens() < 3 )
{
listener.write("Usage: =Tell=user name=message...");
listener.newLine();
}
else
{
String tell = tokenizer.nextToken(); // =tell
String user = tokenizer.nextToken(); // =user
int prefixLength = tell.length() + user.length() + 3;
String message = line.substring( prefixLength ); // =message
// Is the user here?
if( sm_listeners.containsKey(user) )
{
BufferedWriter out = ((BufferedWriter) sm_listeners.get( user ));
if( user.compareTo( m_name ) == 0 )
{
out.write( "You tell yourself: " + message );
out.newLine();
}
else
{
out.write( m_name + " tells you: " + message );
out.newLine();
}
out.flush();
}
else
{
listener.write("=== No such user ===");
listener.newLine();
}
}
tokenizer = null;
listener.flush();
}
catch( Exception e )
{
System.out.println("Tell error: " + e );
}
}
protected void finalize()
{
try
{
m_outToClient.close();
m_inFromClient.close();
m_socket.close();
}
catch( Exception e )
{
System.out.println("Finalize exception: " + e);
}
}
}
|
|
#3
|
|||
|
|||
|
The loop in ChatClient_Recv() blocks. Duh. Nevermind.
Now the question I have is only how do you get a text area to display messages from a server? Is there an actionListener that does this? Any examples? Thanks again. |
|
#4
|
|||
|
|||
|
chatclient
hi there, well i was taking a look in the code, but i can not make it work... im basicly new in java, i just have 3 weeks... but my final homework is to make an chatclient... and i was wondering if you could helpme, send me just the basic code to be able to do it.
it must contain applets.. if someone could help would be great. Thanx AgeManiac |
![]() |
| Viewing: Dev Articles Community Forums > Programming > Java Development > Chat Client code - make it go. |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|