Advertisement

Udemy WW Udemy WW
Showing posts with label Socket. Show all posts
Showing posts with label Socket. Show all posts

Thursday, 8 December 2011

Socket Programming in java( Simple Chat Program)

Program For Server
import java.io.*;
import java.net.*;

public class MyServer
{
ServerSocket ss;
Socket s;
DataInputStream din;
DataOutputStream dout;
public MyServer()
{
try{

System.out.println("Server START......");
ss=new ServerSocket(8);
s=ss.accept();
System.out.println("Client Connected.....");
din=new DataInputStream(s.getInputStream());
dout=new DataOutputStream(s.getOutputStream());
chat();
}catch(Exception e){System.out.println(e);}
}

public void chat()throws IOException
{
String str=" ";
do{
str=din.readUTF();
System.out.println("Client Message: "+str);
dout.writeUTF("I have recieved ur message:"+str);
dout.flush();

}while(!str.equals("stop"));

}

public static void main(String arg[])
{
new MyServer();
}

}

Open console and Compile it and run it
C:\java MyServer

Client Program

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

public class MyClient
{
Socket s;
DataInputStream din;
DataOutputStream dout;
public MyClient()
{
try{
s=new Socket("127.0.0.1",8);
System.out.println(s);
din=new DataInputStream(s.getInputStream());
dout=new DataOutputStream(s.getOutputStream());
chat();
}catch(Exception e){System.out.println(e);}
}

public void chat()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 arg[])
{
new MyClient();
}

}


Now open a new console window and compile it an execute as follows

c:\java MyClient
hello
start your chatting now

Advertisement

Udemy WW