Tuesday, December 25, 2007

Java Server /Client Chat program

/* This is an Client to Server One way comm. program
i.e client (writes) send data ,server keep on (read )listen and recv.

For two way communication between server and client we should go for thread.
How can be acheived by thread ?
In both server and client two threads should be created and one for read() and another for write().since read is blocking call.
For thread reference see my next post "Java Thread Simple program ".

Server.Java */

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
ServerSocket serverSocket=null;
Socket socket=null;
InputStream in=null;
OutputStream out=null;

Server() throws IOException{
serverSocket=new ServerSocket(500);
System.out.println("Server Started");
/* server will blocked here till client connects */
socket=serverSocket.accept();
System.out.println("Connected.........");
/* Any in coming dada we stored in this stream */
in=socket.getInputStream();
out=socket.getOutputStream();
}

void read() throws IOException{
int c=0;
/* printing the incoming message from input stream obj */
while((c=in.read())!=-1){
System.out.print((char)c);
}
in.close();
out.close();
socket.close();
}


public static void main(String[] args) throws IOException {
Server ser=new Server();
ser.read();
/*
Test code for string to byte conversion
String str="arun kumar";
Here we reading array string so we used byte array stream
ByteArrayInputStream by=new ByteArrayInputStream(str.getBytes());
int c=0;
while((c=by.read())!=-1){
System.out.println((char)c);
*/
}
}

/********* End of server *****************/

/*Client.Java */

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.DataInputStream;
public class Client {

Socket socket=null;
InputStream in=null;
OutputStream out=null;

Client() throws UnknownHostException, IOException{
socket=new Socket("localhost",500);
in=socket.getInputStream();
out=socket.getOutputStream();
}

void write() throws IOException{
/* Buffered input Stream will blocked till Enter key pressed. System.in is used get input from console (kbd) */
BufferedInputStream input=new BufferedInputStream(System.in);
while(true){
/* but here we converting buffer data to stream of bytes since buffer stream will store a block of characters*/
int c=input.read();
System.out.print((char)c);
out.write(c);

}
}
public static void main(String[] args) {
try {
Client client=new Client();
client.write();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

}

/********** End of Client *******************/

No comments: