Pages

Wednesday, February 9, 2011

Java Client - Server chat --- very Basic SOCKET PROGRAMMING

Compile both Programs and create clas files
Open 2 cmd's .In one of thos enter
java server
and in other
java client


server.java

import java.net.*;
import java.io.*;
public class server
{
public static void main(String [] ar)
{
int port = 6666;
try
{
ServerSocket ss=new ServerSocket(port);
System.out.println("Waiting for a client....");
Socket socket=ss.accept();
System.out.println("Got a client...");
System.out.println();
InputStream sin=socket.getInputStream();
OutputStream sout=socket.getOutputStream();
DataInputStream in=new DataInputStream(sin);
DataOutputStream out=new DataOutputStream(sout);
String line=null;
while(true)
{
line=in.readUTF();
System.out.println("Client send me this line : "+ line);
System.out.println("I'm sending it back...");
out.writeUTF(line);
out.flush();
System.out.println("Waiting for the next line....");
System.out.println();

}

}
catch(Exception x)
{
x.printStackTrace();
}
}
}

client.java

import java.net.*;
import java.io.*;
public class client
{
public static void main(String [] ar)
{
int serverPort = 6666;

String address="127.0.0.1";
try
{
InetAddress ipAddress=InetAddress.getByName(address);
System.out.println("Any of you heard of a socket with IP Address " + address + " And Port " + serverPort + "?");
Socket socket=new Socket(ipAddress, serverPort);
System.out.println("Yes ! i just got hold of the program");
InputStream sin =socket.getInputStream();
OutputStream sout=socket.getOutputStream();
DataInputStream in=new DataInputStream(sin);
DataOutputStream out=new DataOutputStream(sout);
BufferedReader keyboard=new BufferedReader(new InputStreamReader(System.in));
String line=null;
System.out.println("Type in somethg and press enter.will send it to server n tell you wat it thinks");
System.out.println();
while(true)
{
line=keyboard.readLine();
System.out.println("Sending this line to server...");
out.writeUTF(line);

out.flush();
line =in.readUTF();
System.out.println("The server wa very pollite.it send me this " + line);
System.out.println("Looks like the server is pleased.go n enter more lines");
System.out.println();
}

}
catch(Exception x)
{
x.printStackTrace();
}
}
}

No comments:

Post a Comment