Saturday, 14 December 2013

Chat Server

Chat server application in core java-


Very simple chat server application for client and server communication. Open Netbeans IDE and start develop your application. First go to file and select new project.



Select Java and list shown in another box and select Java Application
  

Create project as MyClient    
   

Click Finish.
Project structure is created as shown below,


Open MyClient.java 


Write code for client as shown below,

import java.io.*;
import java.net.*;
public class MyClient
{
Socket s;
DataInputStream din;
DataOutputStream dout;
public MyClient()
{
   try{
s=new Socket("localhost",10);
System.out.println(s);
        din=new DataInputStream(s.getInputStream());
        dout=new DataOutputStream(s.getOutputStream()); 
clientChat();
}
catch(Exception e)
{
   System.out.println(e);
}
     }
public void clientChat()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                     String s1;
do
{
   s1=br.readLine();
                         dout.writeUTF(s1);
                         dout.flush();
                          System.out.println("server Message:"+din.readUTF());
  }
while(!s1.equals("stop"));
  }
public static void main(String ar[])
{
                          new MyClient();
}
}


After that debug your code and run it.


In run window shown your system socket ( IP Address of your machine)


After that follow same steps for creating server application


Write code for server as shown blow,

import java.io.*;
import java.net.*;
public class MyServer
{
ServerSocket ss;
Socket s;
DataInputStream dis;
DataOutputStream dos;

public  MyServer()
{
 try{ 
System.out.println("Server Started");
ss= new ServerSocket(10);
s=ss.accept();
System.out.println(s);
System.out.println("client connected");
dis=new DataInputStream(s.getInputStream());
dos=new DataOutputStream(s.getOutputStream());
ServerChat();
}
catch(Exception e)
{System.out.println(e);
}}
public static void main (String s[])
{ new MyServer();}
public void ServerChat() throws IOException
{
String str;
do
{
str=dis.readUTF();
System.out.println("client message "+str);
dos.writeUTF("hello dear \n"+str);
dos.flush();
}
while(!str.equals("stop"));
}}






And run server application the output window show message server started


Client is already running so in few seconds server output window will display client connected 


Go to your client run output window and write message here as, shown below and then press enter

Open server output window here client message will be display as,


In client output window message will be print which is server response 


This server handle only one client. So this is single client server, singe thread server.
If you want to run multiple client use multithread. All servers are multithreaded.











No comments:

Post a Comment