Monday, December 29, 2008

DOS Chat -- Java Networking II

Save the programs in a folder.

compile both programs

copy the class files to different computers if necessary

execute the Server first (java Server)

execute the Client by passing a parameter as the ipaddress of the computer that has the Server running on it .(eg. java Client 10.0.1.13)
The Chat continues until either side sends "bye" in the message.
Client.java
----------------------------------------------------------------
import java.net.*;
import java.io.*;

public class Client
{
public static void main(String args[]) throws IOException
{
int PORT = 8134;
InputStream inStream;
DataInputStream inDataStream;
OutputStream outStream;
DataOutputStream outDataStream;
String message = "";

InetAddress host = InetAddress.getLocalHost();
String diffHost = args[0];
Socket sock = new Socket(diffHost,PORT);
System.out.println("Chat Client Started");
do{
System.out.println("Enter your message here: ");
DataInputStream dis = new DataInputStream(System.in);
message = dis.readLine();
outStream = sock.getOutputStream();
outDataStream = new DataOutputStream (outStream);
outDataStream.writeUTF(message);

inStream = sock.getInputStream ();
inDataStream = new DataInputStream ( inStream );
message = inDataStream.readUTF();
System.out.println("Server Sent: "+message);
}while(!message.equals("bye"));
}
}
----------------------------------------------------------------
Server.java
----------------------------------------------------------------
import java.io.*;
import java.net.*;

public class Server
{
public static void main(String[] args) throws IOException
{
int PORT = 8134;
InputStream inStream;
DataInputStream inDataStream;
OutputStream outStream;
DataOutputStream outDataStream;
String message="";
String received="";

System.out.println("Chat Server Started");

ServerSocket sock = new ServerSocket(PORT);
Socket conn = sock.accept();
do{
inStream = conn.getInputStream ();
inDataStream = new DataInputStream ( inStream );
message = inDataStream.readUTF();
System.out.println("Client sent: "+message);

DataInputStream dis = new DataInputStream(System.in);
message = dis.readLine();
outStream = conn.getOutputStream();
outDataStream = new DataOutputStream (outStream);
System.out.println("Enter your message here: ");
outDataStream.writeUTF(message);
}while(!message.equals("bye"));
conn.close();
}
}
----------------------------------------------------------------

No comments: