RSS

Monthly Archives: April 2010

MySQL Case-Sensitive Query

MySQL queries are not case-sensitive by default. Following is a simple query that is looking for ‘value’. However it will return ‘VALUE’, ‘value’, VaLuE’, etc…

SELECT *  FROM `table` WHERE `column` = ‘value’

The good news is that if you need to make a case-sensitive query, it is very easy to do:

SELECT *  FROM `table` WHERE BINARY `column` = ‘value’
Advertisements
 
Leave a comment

Posted by on April 26, 2010 in MySQL Server

 

Setting up Subversion on Windows

When it comes to readily available, free source control, I don’t think you can do better than Subversion at the moment. I’m not necessarily advocating Subversion; there are plenty of other great source control systems out there — but few can match the ubiquity and relative simplicity of Subversion. Beyond that, source control is source control, as long as you’re not using Visual SourceSafe. And did I mention that Subversion is … free?

Allow me to illustrate how straightforward it is to get a small Subversion server and client going on Windows. It’ll take all of 30 minutes, tops, I promise. And that’s assuming you read slowly.

The first thing we’ll do is download the latest Subversion Windows binary installer. At the time of writing, that’s 1.46. I recommend overriding the default install path and going with something shorter:

c:\svn\

Note that the installer adds c:\svn\bin to your path, so you can launch a command prompt and start working with it immediately. Let’s create our first source repository, which is effectively a system path.

svnadmin create "c:\svn\repository"

Within that newly created folder, uncomment the following lines in the conf/svnserve.conf file by removing the pound character from the start of each line:

anon-access = none
auth-access = write
password-db = passwd

Next, add some users to the conf/passwd file. You can uncomment the default harry and sally users to play with, or add your own:

harry = harryssecret
sally = sallyssecret

As of Subversion 1.4, you can easily install Subversion as a Windows service, so it’s always available. Just issue the following command:

sc create svnserver binpath= "c:\svn\bin\svnserve.exe --service -r c:\svn\repository"
displayname= "Subversion" depend= Tcpip start= auto

It’s set to auto-start so it will start up automatically when the server is rebooted, but it’s not running yet. Let’s fix that:

net start svnserver

Note that the service is running under the Local System account. Normally, this is OK, but if you plan to implement any Subversion hook scripts later, you may want to switch the service identity to an Administrator account with more permissions. This is easy enough to do through the traditional Windows services GUI.

Subversion service screenshot

Now let’s verify that things are working locally by adding a root-level folder in source control for our new project, aptly named myproject.

set SVN_EDITOR=c:\windows\system32\notepad.exe
svn mkdir svn://localhost/myproject

It’s a little weird when running locally on the server, as Subversion will pop up a copy of Notepad with a place for us to enter commit comments. Every good programmer always comments their source control actions, right?

Subversion local commit, notepad comment

Enter whatever comment you like, then save and close Notepad. You’ll be prompted for credentials at this point; ignore the prompt for Administrator credentials and press enter. Use the credentials you set up earlier in the conf/passwd file. If everything goes to plan, you should be rewarded with a “committed revision 1” message.

svn mkdir svn://localhost/myproject
Authentication realm: <svn://localhost:3690>
Password for 'Administrator': [enter]
Authentication realm: <svn://localhost:3690>
Username: sally
Password for 'sally': ************

Committed revision 1.

Congratulations! You just checked your first change into source control!

We specified svn:// as the prefix to our source control path, which means we’re using the native Subversion protocol. The Subversion protocol operates on TCP port 3690, so be sure to poke an appropriate hole in your server’s firewall, otherwise clients won’t be able to connect.

Now that the server’s good to go, let’s turn our attention to the client. Most people use TortoiseSVN to interact with Subversion. Download the latest 32-bit or 64-bit Windows client (1.4.8.12137 as of this writing) and install it. The installer will tell you to reboot, but you don’t have to.

Now create a project folder somewhere on your drive. I used c:\myproject. Tortoise isn’t a program so much as a shell extension. To interact with it, you right click in Explorer. Once you’ve created the project folder, right click in it and select “SVN Checkout…”

Tortoise 'SVN Checkout...'

Type svn://servername/myproject/ for the repository URL and click OK.

Tortoise checkout dialog

Tortoise now associates the c:\myproject folder with the svn://servername/myproject path in source control. Anything you do on your local filesystem path (well, most things– there are some edge conditions that can get weird) can be checked back in to source control.

There’s a standard convention in Subversion to start with the “TTB folders” at the root of any project:

Because Subversion uses regular directory copies for branching and tagging (see Chapter 4, Branching and Merging), the Subversion community recommends that you choose a repository location for each project root — the “top-most” directory which contains data related to that project — and then create three subdirectories beneath that root: trunk, meaning the directory under which the main project development occurs; branches, which is a directory in which to create various named branches of the main development line; tags, which is a collection of tree snapshots that are created, and perhaps destroyed, but never changed.

Of course, none of this means your developers will actually understand branching and merging, but as responsible Subversion users, let’s dutifully add the TTB folders to our project. Note that we can batch up as many changes as we want and check them all in atomically as one unit. Once we’re done, right click the folder and select “SVN Commit…”

Tortoise 'SVN Commit...'

In the commit dialog, indicate that yes, we do want to check in these files, and we always enter a checkin comment– right? right?

Tortoise Commit dialog

You’ll have to enter your server credentials here, but Tortoise will offer to conveniently cache them for you. Once the commit completes, note that the files show up in the shell with source control icon overlays:

Tortoise folder with source control icon overlays

And now we’re done. Well, almost. There are a few settings in Tortoise you need to pay special attention to. Right click and select “TortoiseSVN, Settings”.

  1. See that hidden “.svn” folder? These folders are where Subversion puts its hidden metadata schmutz so it can keep track of what you’re doing in the local filesystem and resolve those changes with the server. The default naming convention of these folders unfortunately conflicts with some fundamental ASP.NET assumptions. If you’re an ASP.NET 1.x developer, you need to switch the hidden folders from “.svn” to “_svn” format, which is on the General options page. This hack is no longer necessary in ASP.NET 2.0 or newer.
  2. I’ll never understand why, but by default, Tortoise tries to apply source control overlays across every single folder and drive on your system. This can lead to some odd, frustrating file locking problems. Much better to let Tortoise know that it should only work its shell magic on specific folders. Set this via “Icon Overlays”; look for the exclude and include paths. I set the exclude path to everything, and the include path to only my project folder(s).tortoise exclude and include paths

Unfortunately, since Tortoise is a shell extension, setting changes may mean you need to reboot. You can try terminating and restarting explorer.exe, but I’ve had mixed results with that.

And with that, we’re done. You’ve successfully set up a Subversion server and client. A modern client-server source control system inside 30 minutes — not bad at all. As usual, this is only intended as the gentlest of introductions; I encourage you to check out the excellent Subversion documentation for more depth.

I find Subversion to be an excellent, modern source control system. Any minor deficiencies it has (and there are a few, to be clear) are more than made up by its ubiquity, relative simplicity, and robust community support. In the interests of equal time, however, I should mention that some influential developers — most notably Linus Torvaldshate Subversion and view it as an actual evil. There’s an emerging class of distributed revision control that could eventually supercede existing all the centralized source control systems like Subversion, Vault, Team System, and Perforce.

I’m skeptical. I’ve met precious few developers that really understood the versioning concepts in the simple centralized source control model. I have only the vaguest of hopes that these developers will be able to wrap their brains around the vastly more complicated and powerful model of distributed source control. It took fifteen years for centralized source control usage to become mainstream, so a little patience is always advisable.

Referenced by: http://www.codinghorror.com/blog/2008/04/setting-up-subversion-on-windows.html

http://www.subversionary.org/howto/setting-up-a-subversion-server-on-windows-server-2003

http://nedbatchelder.com/text/quicksvn.html

http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-serversetup-apache.html

http://lifehacker.com/188582/hack-attack-how-to-set-up-a-personal-home-subversion-server

 
Leave a comment

Posted by on April 19, 2010 in Control Version, SVN

 

Make Java Application as Windows Service

Let’s say that we want to create a Windows Installer package for the included Java Service example. This tutorial will present in detail how to achieve this goal. In order to replicate it on your own machine, you need to have a (latest) Sun JDK installed.

Before you start the tutorial download and unzip the Java Service Example. It contains all the files necessary to accomplish this tutorial.

1. Prepare a Java application for running as a service

You have the choice of using the supplied example application or making your own. In order for a Java application to work correctly as a service you must implement 2 methods in its main class:

public static void main(String argv[])
{
  // implementation goes here
}

public static void stop()
{
  // implementation goes here
}

The main() method will be called when the service starts and the stop() method will be called when service must stop or the computer is shutting down.

2. Create project

Start Advanced Installer by selecting it from the “Start” menu. Launching Advanced Installer automatically starts a new installation project. Choose “Java” > “Java Application” as the project type.

New Project

Save A good idea is to save and name the project at this point. Use the “Save” menu item under the “File” menu or the Ctrl+S keyboard shortcut and let’s name it javaserviceexample.aip.

3. Enter Product Details

Product Details

Please note that these details are completely fictive.

4. Set Install Parameters

Install Parameters Get to the Install Parameters page by clicking “Install Parameters” on the left side page menu. We won’t change anything here, leaving everything to their default values.

5. Add Installation Files

Files and Folders Go to the Files and Folders page by clicking on “Files and Folders” on the left side page menu.

Add Folder Right click “Application Folder” and select “Add Files”. Browse to where you unzipped the Java Service example then go to the lib folder and select the Java Services example jar archive “javaservice.jar”. Click Ok.

Files, Folders and Shortcuts

6. Define Java Products

Java  Products Go to the Java Products page by clicking on “Java Products” on the left side page menu.

New  Java Product Create a new [ Java Product ] by clicking on the New Product toolbar button. Let’s call it javaservice.

Java Products

Click on the [ Add JAR(s)… ] button and browse to and select the javaservice.jar file. Click Ok.

Edit the Main class to: com.caphyon.service.JavaService.

At the application type select “Win32 Service”.

Product Settings

Now a new file has appeared in the Files and Folders Page: javaservice.exe.

NoteIf the service terminates unexpectedly from time to time or when the user logs off, the Java Virtual Machine may receive incorrect signals. This can be fixed by using the Reduced usage of operating-system signals (-Xrs) option in the Edit JVM Parameters dialog (it can be launched from the Virtual Machine tab).

7. Define the Service

Services Go to the Services page by clicking on “Services” in the Project Details.

7.1 Install a new service

New Service Click on “Services to Install” and select “New Service Installation”. In the “Choose Instalation Dialog” click on “Application Folder” and select “javaservice.exe”.

New Java Service

7.2 Enter service properties

Leave Service Name unchanged.

Edit the Display Name: Java Service Example.

Edit the Description: This a Java Service Example.

Leave the Service Parameters, Service context and Service Account unchanged.

Installed Service Properties

7.3 Setup the control actions

New Service Control Operation Right click on “Control Action” and select “New Service Operation”.

Edit the Service Name to: javaservice.exe.

Leave anything else unchanged.

Sevice Control Parameters

8. Build

Build Click on the [ Build ] toolbar button.

9. Run, test and remove

Click on the [ Run ] toolbar button to run and test the MSI you created. After installation you should have a new service installed.

To test the application open console and enter the following command: telnet localhost 4444. You should see:

Java Service is running
                        
Connection to host lost

You also can build Java Service Example msi package using ant. Open a console window and change current directory to the directory where you unzipped the Java Service example archive. Execute the following command: ant msi.

To remove the installed package, simply Run it again and select Remove. That’s it!

Referenced by: http://www.advancedinstaller.com/user-guide/tutorial-java-service.html

 
Leave a comment

Posted by on April 8, 2010 in Java Pro

 

Print iReport in Java Code

Choosing a printer programmatically in Jasper Reports


JasperPrint print = JasperFillManager.<strong>fillReport</strong>(  this.class.<strong>getResource</strong>("<em>/classpath/yourReport.jasper</em>").<strong>getPath</strong>(),  new <strong>HashMap</strong>(), new <strong>yourReportDataSource</strong>());
 PrinterJob job = PrinterJob.getPrinterJob();
 /* Create an array of PrintServices */
 PrintService[] services = PrintServiceLookup.<strong>lookupPrintServices</strong>(null,  null);
 int selectedService = 0;
 /* Scan found services to see if anyone suits our needs */
 for(int i = 0; i < services.length;i++){
 if(services[i].<strong>getName</strong>().<strong>toUpperCase</strong>().<strong>contains</strong>("<em>Your  printer's name</em>")){
 /*If the service is named as what we are querying we select it */
 selectedService = i;
 }
 }
 job.<strong>setPrintService</strong>(services[selectedService]);
 PrintRequestAttributeSet printRequestAttributeSet = new <strong>HashPrintRequestAttributeSet</strong>();
 MediaSizeName mediaSizeName = MediaSize.<strong>findMedia</strong>(4,4,MediaPrintableArea.INCH);
 printRequestAttributeSet.<strong>add</strong>(mediaSizeName);
 printRequestAttributeSet.<strong>add</strong>(new Copies(1));
 JRPrintServiceExporter exporter;
 exporter = new <strong>JRPrintServiceExporter</strong>();
 exporter.<strong>setParameter</strong>(JRExporterParameter.JASPER_PRINT,  print);
 /* We set the selected service and pass it as a paramenter */
 exporter.<strong>setParameter</strong>(JRPrintServiceExporterParameter.PRINT_SERVICE,  services[selectedService]);
 exporter.<strong>setParameter</strong>(JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET,  services[selectedService].getAttributes());
 exporter.<strong>setParameter</strong>(JRPrintServiceExporterParameter.PRINT_REQUEST_ATTRIBUTE_SET,  printRequestAttributeSet);
 exporter.<strong>setParameter</strong>(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG,  Boolean.FALSE);
 exporter.<strong>setParameter</strong>(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG,  Boolean.TRUE);
 exporter.exportReport();

In the above code you can see how to accomplish our purpose. The first part of all is generating our JasperPrint, this is common to all methods of report printing. Then comes the important part. First we look for the available printServices in the computer. Second, we scan the found services to see if there is anyone that suits our needs. Finally we set the selected print service in the exporter.

You will also find methods to choose the paper output and the number of copies to print.

Reference by:  http://blog.marcnuri.com/blog/default/2007/03/22/Choosing-a-printer-programmatically-in-Jasper-Reports

 
3 Comments

Posted by on April 6, 2010 in Java

 

Multithreaded Chat Server by Nakov Chat

Multithreaded Chat Client/Server Design Diagram

Multithreaded Chat Server Implementation – Nakov Chat Server

/**

* Nakov Chat Server

* (c) Svetlin Nakov, 2002

* http://www.nakov.com

*

* Nakov Chat Server is multithreaded chat server. It accepts multiple clients

* simultaneously and serves them. Clients can send messages to the server.

* When some client send a message to the server, this message is dispatched

* to all the clients connected to the server.

*

* The server consists of two components – “server core” and “client handlers”.

*

* The “server core” consists of two threads:

*   – NakovChatServer – accepts client connections, creates client threads to

* handle them and starts these threads

*   – ServerDispatcher – waits for a messages and sends arrived messages to

* all the clients connected to the server

*

* The “client handlers” consist of two threads:

*   – ClientListener – listens for message arrivals from the socket and

* forwards them to the ServerDispatcher thread

*   – ClientSender – sends messages to the client

*

* For each accepted client, a ClientListener and ClientSender threads are

* created and started. A ClientInfo object is also created to contain the

* information about the client. Also the ClientInfo object is added to the

* ServerDispatcher’s clients list. When some client is disconnected, is it

* removed from the clients list and both its ClientListener and ClientSender

* threads are interrupted.

*

*

* NakovChatServer class is entry point for the program. It opens a server

* socket, starts the dispatcher thread and infinitely accepts client connections,

* creates threads for handling them and starts these threads.

*/

import java.net.*;

import java.io.*;

public class NakovChatServer

{

public static final int LISTENING_PORT = 2002;

public static void main(String[] args)

{

// Open server socket for listening

ServerSocket serverSocket = null;

try {

serverSocket = new ServerSocket(LISTENING_PORT);

System.out.println(“NakovChatServer started on port ” + LISTENING_PORT);

} catch (IOException se) {

System.err.println(“Can not start listening on port ” + LISTENING_PORT);

se.printStackTrace();

System.exit(-1);

}

// Start ServerDispatcher thread

ServerDispatcher serverDispatcher = new ServerDispatcher();

serverDispatcher.start();

// Accept and handle client connections

while (true) {

try {

Socket socket = serverSocket.accept();

ClientInfo clientInfo = new ClientInfo();

clientInfo.mSocket = socket;

ClientListener clientListener =

new ClientListener(clientInfo, serverDispatcher);

ClientSender clientSender =

new ClientSender(clientInfo, serverDispatcher);

clientInfo.mClientListener = clientListener;

clientInfo.mClientSender = clientSender;

clientListener.start();

clientSender.start();

serverDispatcher.addClient(clientInfo);

} catch (IOException ioe) {

ioe.printStackTrace();

}

}

}

}

/**

* Nakov Chat Server

* (c) Svetlin Nakov, 2002

*

* ServerDispatcher class is purposed to listen for messages received

* from clients and to dispatch them to all the clients connected to the

* chat server.

*/

import java.net.*;

import java.util.*;

public class ServerDispatcher extends Thread

{

private Vector mMessageQueue = new Vector();

private Vector mClients = new Vector();

/**

* Adds given client to the server’s client list.

*/

public synchronized void addClient(ClientInfo aClientInfo)

{

mClients.add(aClientInfo);

}

/**

* Deletes given client from the server’s client list

* if the client is in the list.

*/

public synchronized void deleteClient(ClientInfo aClientInfo)

{

int clientIndex = mClients.indexOf(aClientInfo);

if (clientIndex != -1)

mClients.removeElementAt(clientIndex);

}

/**

* Adds given message to the dispatcher’s message queue and notifies this

* thread to wake up the message queue reader (getNextMessageFromQueue method).

* dispatchMessage method is called by other threads (ClientListener) when

* a message is arrived.

*/

public synchronized void dispatchMessage(ClientInfo aClientInfo, String aMessage)

{

Socket socket = aClientInfo.mSocket;

String senderIP = socket.getInetAddress().getHostAddress();

String senderPort = “” + socket.getPort();

aMessage = senderIP + “:” + senderPort + ” : ” + aMessage;

mMessageQueue.add(aMessage);

notify();

}

/**

* @return and deletes the next message from the message queue. If there is no

* messages in the queue, falls in sleep until notified by dispatchMessage method.

*/

private synchronized String getNextMessageFromQueue()

throws InterruptedException

{

while (mMessageQueue.size()==0)

wait();

String message = (String) mMessageQueue.get(0);

mMessageQueue.removeElementAt(0);

return message;

}

/**

* Sends given message to all clients in the client list. Actually the

* message is added to the client sender thread’s message queue and this

* client sender thread is notified.

*/

private synchronized void sendMessageToAllClients(String aMessage)

{

for (int i=0; i<mClients.size(); i++) {

ClientInfo clientInfo = (ClientInfo) mClients.get(i);

clientInfo.mClientSender.sendMessage(aMessage);

}

}

/**

* Infinitely reads messages from the queue and dispatch them

* to all clients connected to the server.

*/

public void run()

{

try {

while (true) {

String message = getNextMessageFromQueue();

sendMessageToAllClients(message);

}

} catch (InterruptedException ie) {

// Thread interrupted. Stop its execution

}

}

}

/**

* Nakov Chat Server

* (c) Svetlin Nakov, 2002

*

* ClientInfo class contains information about a client, connected to the server.

*/

import java.net.Socket;

public class ClientInfo

{

public Socket mSocket = null;

public ClientListener mClientListener = null;

public ClientSender mClientSender = null;

}

/**

* Nakov Chat Server – (c) Svetlin Nakov, 2002

*

* ClientListener class is purposed to listen for client messages and

* to forward them to ServerDispatcher.

*/

import java.io.*;

import java.net.*;

public class ClientListener extends Thread

{

private ServerDispatcher mServerDispatcher;

private ClientInfo mClientInfo;

private BufferedReader mIn;

public ClientListener(ClientInfo aClientInfo, ServerDispatcher aServerDispatcher)

throws IOException

{

mClientInfo = aClientInfo;

mServerDispatcher = aServerDispatcher;

Socket socket = aClientInfo.mSocket;

mIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));

}

/**

* Until interrupted, reads messages from the client socket, forwards them

* to the server dispatcher’s queue and notifies the server dispatcher.

*/

public void run()

{

try {

while (!isInterrupted()) {

String message = mIn.readLine();

if (message == null)

break;

mServerDispatcher.dispatchMessage(mClientInfo, message);

}

} catch (IOException ioex) {

// Problem reading from socket (communication is broken)

}

// Communication is broken. Interrupt both listener and sender threads

mClientInfo.mClientSender.interrupt();

mServerDispatcher.deleteClient(mClientInfo);

}

}

/**

* Nakov Chat Server – (c) Svetlin Nakov, 2002

*

* Sends messages to the client. Messages are stored in a message queue. When

* the queue is empty, ClientSender falls in sleep until a new message is

* arrived in the queue. When the queue is not empty, ClientSender sends the

* messages from the queue to the client socket.

*/

import java.io.*;

import java.net.*;

import java.util.*;

public class ClientSender extends Thread

{

private Vector mMessageQueue = new Vector();

private ServerDispatcher mServerDispatcher;

private ClientInfo mClientInfo;

private PrintWriter mOut;

public ClientSender(ClientInfo aClientInfo, ServerDispatcher aServerDispatcher)

throws IOException

{

mClientInfo = aClientInfo;

mServerDispatcher = aServerDispatcher;

Socket socket = aClientInfo.mSocket;

mOut = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));

}

/**

* Adds given message to the message queue and notifies this thread

* (actually getNextMessageFromQueue method) that a message is arrived.

* sendMessage is called by other threads (ServeDispatcher).

*/

public synchronized void sendMessage(String aMessage)

{

mMessageQueue.add(aMessage);

notify();

}

/**

* @return and deletes the next message from the message queue. If the queue

* is empty, falls in sleep until notified for message arrival by sendMessage

* method.

*/

private synchronized String getNextMessageFromQueue() throws InterruptedException

{

while (mMessageQueue.size()==0)

wait();

String message = (String) mMessageQueue.get(0);

mMessageQueue.removeElementAt(0);

return message;

}

/**

* Sends given message to the client’s socket.

*/

private void sendMessageToClient(String aMessage)

{

mOut.println(aMessage);

mOut.flush();

}

/**

* Until interrupted, reads messages from the message queue

* and sends them to the client’s socket.

*/

public void run()

{

try {

while (!isInterrupted()) {

String message = getNextMessageFromQueue();

sendMessageToClient(message);

}

} catch (Exception e) {

// Commuication problem

}

// Communication is broken. Interrupt both listener and sender threads

mClientInfo.mClientListener.interrupt();

mServerDispatcher.deleteClient(mClientInfo);

}

}

Client For Nakov Chat Server

/**

* Nakov Chat Client

* (c) Svetlin Nakov, 2002

* http://www.nakov.com

*

* NakovChatClient connects to Nakov Chat Server and prints all the messages

* received from the server. It also allows the user to send messages to the

* server. NakovChatClient thread reads messages and print them to the standard

* output. Sender thread reads messages from the standard input and sends them

* to the server.

*/

import java.io.*;

import java.net.*;

public class NakovChatClient

{

public static final String SERVER_HOSTNAME = “localhost”;

public static final int SERVER_PORT = 2002;

public static void main(String[] args)

{

BufferedReader in = null;

PrintWriter out = null;

try {

// Connect to Nakov Chat Server

Socket socket = new Socket(SERVER_HOSTNAME, SERVER_PORT);

in = new BufferedReader(

new InputStreamReader(socket.getInputStream()));

out = new PrintWriter(

new OutputStreamWriter(socket.getOutputStream()));

System.out.println(“Connected to server ” +

SERVER_HOSTNAME + “:” + SERVER_PORT);

} catch (IOException ioe) {

System.err.println(“Can not establish connection to ” +

SERVER_HOSTNAME + “:” + SERVER_PORT);

ioe.printStackTrace();

System.exit(-1);

}

// Create and start Sender thread

Sender sender = new Sender(out);

sender.setDaemon(true);

sender.start();

try {

// Read messages from the server and print them

String message;

while ((message=in.readLine()) != null) {

System.out.println(message);

}

} catch (IOException ioe) {

System.err.println(“Connection to server broken.”);

ioe.printStackTrace();

}

}

}

class Sender extends Thread

{

private PrintWriter mOut;

public Sender(PrintWriter aOut)

{

mOut = aOut;

}

/**

* Until interrupted reads messages from the standard input (keyboard)

* and sends them to the chat server through the socket.

*/

public void run()

{

try {

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

while (!isInterrupted()) {

String message = in.readLine();

mOut.println(message);

mOut.flush();

}

} catch (IOException ioe) {

// Communication is broken

}

}

}

 
1 Comment

Posted by on April 1, 2010 in Uncategorized