Monday, April 21, 2008

Multi-threaded Socket Server in Java

I have always been curious about how to make a multi-threaded server in Java, and it turns out to be pretty simple to get something basic up and running.

My goal was to create a program that would listen for incoming connections from a client, and repeat whatever is sent to that server. You can see this server work using a telnet session on port 5000.

telnet localhost 5000

Then, whatever you type will be echoed back to you. If you want to quit, just type exit.

Here's the code, consisting of 2 classes.

package sockets;

* Includes main method to get things going
* Otherwise, this just prepares a new ServerSocket that
* listens for new connections
* and starts a new thread for each connection
public class EchoServer {
public void go(){
ServerSocket serverSocket = new ServerSocket(5000);
System.out.print("Listening for connections on port 5000... ");
Socket client = serverSocket.accept();
Thread t = new Thread(new EchoClientHandler(client));
System.out.println("Connected - "+client.getInetAddress());
}catch(Exception e){

public static void main(String[] args) {
EchoServer server = new EchoServer();

* The Runnable job that takes in the new Socket
class EchoClientHandler implements Runnable{

private final BufferedReader reader;
private final PrintWriter output;
private final Socket socket;
private static final String MESSAGE = "ECHO... [?]\r\n";
private static final String EXIT_MESSAGE = "Sad to see you go. Goodbye.\r\n";
private static final String WELCOME_MESSAGE = "Welcome to the Echo Server. Type something to see it echoed back to you!\r\n";

public EchoClientHandler(Socket incomingSocket) throws IOException{
socket = incomingSocket;
output = new PrintWriter(incomingSocket.getOutputStream());
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

public void run(){
String line = null;
while((line = reader.readLine()) != null){
boolean quit = false;
output.write(MESSAGE.replaceAll("\\?", line));
quit = true;
}catch(Exception e){
System.err.println("OUCH! "+e.getMessage());
try{socket.close();}catch(Exception ee){}

Here's how it works.

When the EchoServer starts up, it opens a server socket that listens for incoming connection requests. When it gets a request, it creates a new handler instance, taking the Socket as an argument. The handler is a Runnable class, and used to start a new Thread. The result is that the EchoServer can handle more than one connection at a time -- just like a good socket server should.

To expand on this, it would be a good idea to implement some means of managing the threads and connections. Using the java.util.concurrent API would be a good thing to do to implement some means of thread pooling in the server instead of using naked Threads. Thread pooling is an important thing to implement because each new persistent connection requires a new thread. Too many connections would cause some real resource problems. However, if there are limits to the amount of connections the server will allow, you need to manage connections. Therefore, some intelligence might need to be added to a Client program, so that a connection need only stay alive for a certain amount of time before becoming disconnected. Then, a well designed client might seamlessly create a new connection to the server.

Thursday, April 03, 2008

Social Networks are the Next Commodity

When I need to fly I typically treat myself to a copy of the Economist. In my opinion, it's got some of the best news available in the world. Last week, on a trip to San Diego, I picked up a copy for myself to enjoy.

The March 22 issue had an interesting and compelling article about the future of social networking sites. Essentially, the premises state that social networking is something that will become pervasive and a feature that people come to expect on a site. There's no question that social networking is becoming ubiquitous. You could make the argument that social networks are already a commodity, in the way that because they are everywhere, and cheap or most likely free to participate in, social networking is already a commodity.

OK, what does that mean? It means that the only way to make any money on a primarily social networking platform is to increase volume. Indeed, it's the page views, not the amazing amounts of revenue that make Facebook so highly valued. What I found interesting about the article in the Economist was the part that mentioned how difficult it is to create any sort of solid revenue model based on the high-traffic, social network, advertising only business model. There are some serious limits to the amount of money a business can make with this kind of structure. And it gets worse. Since most social networks don't to anything more useful than poke, attack, or leave a message on a page for a friend, there's not much value for a user to remain loyal to a site he or she is a member of. That means declining page views once the buzz is gone. You can see attempts to maintain buzz by sites like myspace and linkedin constantly adding new features, but in the end, it just makes for a more complicated we application, with a diluted purpose.

So, what's next?

Email for one. The fore-mentioned article makes a point of explaining that email is the best way to really build a rich social network for the sake of networking. That's right, email is the next killer app. Check out Xobni. They're building what I believe is a real and genuine social networking app with purpose. And they integrate it with your email client. I also expect that we'll see some pretty amazing things, with some genuine utility, hitting our mobile phones very soon. When I mention utility, I'm not talking about ridiculous pillow fights or zombie attacks either. With the android platform, and the iPhone SDK, developing real social networking applications that tie into real people doing real things in real time becomes much more of a possibility.

What about social networking sites? I believe that we'll see somewhat of a shake down in the realm of social networks. They will be on plenty of sites, and the smart ones will use some means of identity sharing between them. However, I believe that the social networking destinations will need something of real value to offer their users. Otherwise, with nothing invested, and nothing returned, there's not much reason to build a profile. Eventually, social networking will become the byproduct of something more useful.