Friday, March 9, 2012

The Concept of Sockets and Networking in Java Simplified

A socket is one end-point of a two-way communication link between two programs running on the Package provides support for sockets. Socket classes can be used to implement the connection between a client program and a server program.

ServerSocket class is exclusive for the Server side implementation of the client-server model.

 Java programming with Socket class allows easy implementation of a client-server model for one way or two way communication. We can easily implement a simple one way client server model,2 way client server model,a broad cast server,a multicast server using Sockets and Server Sockets in Java. 


Client Side
 Basically a socket can used in a client to send message it involves creation of socket by using the code

Socket mysocket=new Socket(localhost,2000)

Here a socket is created in the local machine itself you can specify the
ip address of the server machine instead of localhost.

Server Side

In the Sever Side a ServerSocket is created.ServerSocket is a different
class rather than socket.It is meant for the server side only.
In the server side the following code is usually used

ServerSocket ssock=new ServerSocket(2000)

As you can see the same port number should be used in the client and server side.

Classes like PrintStream is used to send message from the client to the server.It is established easily like this

PrintStream ps=new PrintStream(mysocket.getOutputStream)
ps.println("my message");

This code in the client side sends message to the server.In the server 
side this message can be easily accepted and displayed using the 
following code

ServerSocket ssock=new ServerSocket(2000)
Socket mysocket=ssock.accept()
DataInputStream d=new DataInputStream(mysocket.getInputStream)
String msgfromserver=d.readLine() 

The method accept() is used to accept a connection from the client.Note that you need to surround the statements with a try-catch block to handle all the exceptions.
In this way you can send a message from the client to server.


The Source Codes Published in this Blog can be used freely for Educational purposes but should not be reproduced on any other Blog or Website without the consent of the author.