close

Find out more about affordable hosting sollutions:
VPS, JAVA, Web


Toppanel
Using Sockets in Java PDF Print E-mail
Written by Maksym Nesen   
Tuesday, 04 November 2008 15:11
Would you like to create your own chat? Have you realized that you'll have to study socket basics? So, I'll advise you some information about connection between computers using Java. So, do not forget to include in your source code java.net and java.io packages.

Here are 3 steps of creation of our program:
a) Server(I'll call it Tim), is created and waits for connections at the 4444 port.
b) Client (I'll call it Chris), is created and connects to Tim at 4444.
c) Data transfer between Tim and Chris is created and data interchange begins.

To create client socet you should write following code in your program:

Socket clientSocket = null;
clientSocket = new Socket("Tim", 4444);

This socket connects to the computer, which is called Tim at port 4444. Usually instead of 'Tim' computer's IP adress is used. But before to connect to this computer we should start our server socket program on it. To do this we shell create server socket in our Tim program and set it to wait for client requests:

Socket serverSocket = null;
serverSocket = new Socket(4444); //Notice no user to connect to this time.
serverSocket.accept(); //Accept a client.

Now lets transfer data between server and client.

We have a task to get data from client and immidiatelly send another data back to client. To perform such an operation we shell declare PrintWriter stream for output and BufferedReader for input. And we shell declare those streams both at the server and client sides. I'll show how to do it at the client's side:

PrintWriter out = null;
BufferedReader in = null;
Socket clientSocket = null;

clientSocket = new Socket("Tim", 4444);
//get the socket's ouput
out=new PrintWriter(clientSocket.getOutputStream(), true);
//get the socket's input
in=new BufferedReader(new inputStreamReader(clientSocket.getInputStream()));

Now PrintWriter will be output stream which will pass data to socket. So, if you'll perform out.println("Hello server"); operation, the "Hello server" string will be transferred to the server. And at last we shell to establish permanent data receiving at the server side:

PrintWriter out = null;
BufferedReader in = null;
Socket clientSocket = null;
String fromServer;

clientSocket = new Socket("Tim", 4444);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new inputStreamReader( clientSocket.getInputStream()));

// Loop untill there are incoming messages.
while ((fromServer = in.readLine()) != null) {
//Show received message
System.out.println("Server: " + fromServer);
}

out.close();
in.close();
clientSocket.close();