Sunday, December 12, 2010

My Java Socket

Publications by Author


1.      Arun Singh, Ajay k Sharma and Ashish Kumar, “Comparing Centralised and Distributed Servers Using Java Sockets for Small Scale Implementation”, International Journal of Electrical, Electronics and Computer Systems, Bangladesh, volume 1, Issue 2,  pp. 47-52, April 2011, ISSN: 2221-7258.

2.      Arun Singh, Ajay k Sharma and Ashish Kumar, “MultiClient MultiInstance Secured Distributed File Server”, International Journal of Computer Applications, USA (0975-8887), volume 19-No.9, pp. 25-29, April 2011(impact factor 0.835).

3.      Arun Singh, Ajay k Sharma and Ashish Kumar, ”MultiClient MultiInstance File Server using TCP protocol in Java Sockets”, International Journal of Computer Applications, USA (0975-8887),volume23-No.8, pp. 24-29, June 2011 (impact factor 0.835).

More yet to come...

link for c users :http://www.slideshare.net/jignesh/socket-programming-tutorial

Sockets, which provide a mechanism for communication between two computers, have been around since long before the Java language was a glimmer in James Gosling's eye. The language simply lets you use sockets effectively without having to know the details of the underlying operating system.
Sockets reside roughly at the Session Layer of the OSI model (see the diagram). The Session Layer is sandwiched between the application-oriented upper layers and the real-time data communication lower layers. The Session Layer provides services for managing and controlling data flow between two computers. As part of this layer, sockets provide an abstraction that hides the complexities of getting the bits and bytes on the wire for transmission. In other words, sockets allow us to transmit data by having our application indicate that it wants to send some bytes. Sockets mask the nuts and bolts of getting the job done. When you pick up your telephone, you provide sound waves to a sensor that converts your voice into electrically transmittable data. The phone is a human's interface to the telecommunications network. You aren't required to know the details of how your voice is transported, only the party to whom you would like to connect. In the same sense, a socket acts as a high-level interface that hides the complexities of transmitting 1s and 0s across unknown channels.

When you write code that uses sockets, that code does work at the Presentation Layer. The Presentation Layer provides a common representation of information that the Application Layer can use. Say you are planning to connect your application to a legacy banking system that understands only EBCDIC. Your application domain objects store information in ASCII format. In this case, you are responsible for writing code at the Presentation Layer to convert data from EBCDIC to ASCII, and then (for example) to provide a domain object to your Application Layer. Your Application Layer can then do whatever it wants with the domain object. The socket-handling code you write lives only at the Presentation Layer. Your Application Layer doesn't have to know anything about how sockets work.
The socket is the software abstraction used to represent the "terminals" of a connection between two machines. For a given connection, there's a socket on each machine, and you can imagine a hypothetical "cable" running between the two machines with each end of the "cable" plugged into a socket. Of course, the physical hardware and cabling between machines is completely unknown. The whole point of the abstraction is that we don't have to know more than is necessary.
In a nutshell, a socket on one computer that talks to a socket on another computer creates a communication channel. A programmer can use that channel to send data between the two machines. When you send data, each layer of the TCP/IP stack adds appropriate header information to wrap your data. These headers help the stack get your data to its destination. The good news is that the Java language hides all of this from you by providing the data to your code on streams, which is why they are sometimes called streaming sockets. Think of sockets as handsets on either side of a telephone call -- you and I talk and listen on our handsets on a dedicated channel. The conversation doesn't end until we decide to hang up (unless we're using cell phones). And until we hang up, our respective phone lines are busy.
If you need to communicate between two computers without the overhead of higher-level mechanisms like ORBs (and CORBA, RMI, IIOP, and so on), sockets are for you. The low-level details of sockets get rather involved. Fortunately, the Java platform gives you some simple yet powerful higher-level abstractions that make creating and using sockets easy.

Types of sockets
Generally speaking, sockets come in two flavors in the Java language:
* TCP sockets (implemented by the Socket class, which we'll discuss later)
* UDP sockets (implemented by the DatagramSocket class)
TCP and UDP play the same role, but they do it differently. Both receive transport protocol packets and pass along their contents to the Presentation Layer. TCP divides messages into packets (datagrams) and reassembles them in the correct sequence at the receiving end. It also handles requesting retransmission of missing packets. With TCP, the upper-level layers have much less to worry about. UDP doesn't provide these assembly and retransmission requesting features. It simply passes packets along. The upper layers have to make sure that the message is complete and assembled in correct sequence.
In general, UDP imposes lower performance overhead on your application, but only if your application doesn't exchange lots of data all at once and doesn't have to reassemble lots of datagrams to complete a message. Otherwise, TCP is the simplest and probably most efficient choice.
Because most readers are more likely to use TCP than UDP, we'll limit our discussion to the TCP-oriented classes in the Java language

Tuesday, December 7, 2010

Methods to implement Java

Java Sockets
//single one to one client

import java.io.*;
import java.net.*;

/*
Simple client using Java Sockets.

*/
public class SimpleClient {

/*
@param args
*/
public static void main(String[] args) {

// create a socket and find it to the host/port server is listening on.
String host;
int port;

if(args.length==0) {
host = "localhost";
port = 9999;
} else {
host = args[0];
String portStr = args[1];
try {
port = Integer.parseInt(portStr);
} catch (NumberFormatException nfe) {
System.out.println("Whoops, invalid port number. Will default to 9999");
port = 9999;
}
}

try {
System.out.println("Client will attempt connecting to server at host="+ host +" port="+ port +".");
Socket skt = new Socket(host,port);

// ok, got a connection. Let's use java.io.* niceties to read and write from the connection.
BufferedReader myInput = new BufferedReader(new InputStreamReader(skt.getInputStream()));
BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));

PrintStream myOutput = new PrintStream(skt.getOutputStream());

boolean done = false;

while (!done) {

// prompt and read from console
System.out.print("Enter a message, or enter \"done\" to quit: ");
String buf = consoleInput.readLine();

if(buf != null) {
if(buf.equalsIgnoreCase("done")) {
done = true;
} else {

// write something to the server.
myOutput.println(buf);

// see if the server echoes it back.
buf = myInput.readLine();
if(buf != null) {
System.out.println("Client received ["+ buf + "] from the server!");
}

}
} else {
done = true;
}
}

// we're done, let's get out of dodge!
skt.close();
System.out.println("Client is exiting.");


} catch (IOException ex) {
ex.printStackTrace();
System.out.println("Whoops, something bad happened! I'm outta here.");
}


}}


//single one to one server

import java.io.*;
import java.net.*;

/*
Simple server using Java Sockets.

*/
public class SimpleServer implements Runnable{

Socket csocket;

SimpleServer(Socket csocket){
this.csocket = csocket;
}


public static void main(String[] args) {

try {
// First we create a server socket and bind it to port 9999.
ServerSocket myServerSocket = new ServerSocket(9999);
// server processes incoming client connections forever...
while (true) {

// wait for an incoming connection...
System.out.println("Server is waiting for an incoming connection on host=");
System.out.print(InetAddress.getLocalHost().getCanonicalHostName()+" port="+ myServerSocket.getLocalPort());

Socket skt = myServerSocket.accept();
new Thread(new SimpleServer(skt)).start();
}
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("Whoops, something bad happened! I'm outta here.");
}
}

public void run(){

try{


// ok, got a connection. Let's use java.io. niceties to read and write from the connection.
BufferedReader inputFromClient = new BufferedReader(new InputStreamReader(csocket.getInputStream()));
PrintStream outputToClient = new PrintStream(csocket.getOutputStream());



boolean connectionClosed = false;
while(!connectionClosed) {
// attempt to read input from the stream.
String buf = inputFromClient.readLine();

// if we got input, print it out and write a message back to the remote client..
if (buf != null) {
System.out.println("Server read: ["+ buf + "]");
outputToClient.println(buf);
} else {
connectionClosed = true;
}
}

// close the connection.
csocket.close();
System.out.println("Connection to client closed. Server is now going to wait for another connection.");

} catch (IOException ex) {
ex.printStackTrace();
System.out.println("Whoops, something bad happened! I'm outta here.");
}

}

}