ACN-MultihostChat
CLIENT
import java.net.*;
import java.io.*;
public class SocketClient
{
public static void main(String[] args)
{
String host = “localhost”;
int port = 19999;
StringBuffer instr = new StringBuffer();
String TimeStamp;
System.out.println(“SocketClient initialized”);
try
{
InetAddress address = InetAddress.getByName(host);
Socket connection = new Socket(address, port);
BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(bos, “US-ASCII”);
TimeStamp = new java.util.Date().toString();
String process = “Calling the Socket Server on “+ host + ” port ” + port +” at ” + TimeStamp + (char) 13;
osw.write(process);
osw.flush();
BufferedInputStream bis = new BufferedInputStream(connection.
getInputStream());
InputStreamReader isr = new InputStreamReader(bis, “US-ASCII”);
int c;
while ( (c = isr.read()) != 13)
instr.append( (char) c);
connection.close();
System.out.println(instr);
}
catch (IOException f)
{
System.out.println(“IOException: ” + f);
}
catch (Exception g)
{
System.out.println(“Exception: ” + g);
}
}
}
=============================================
Server
import java.net.*;
import java.io.*;
import java.util.*;
public class MultipleSocketServer implements Runnable
{
private Socket connection;
private String TimeStamp;
private int ID;
public static void main(String[] args)
{
int port = 19999;
int count = 0;
try
{
ServerSocket socket1 = new ServerSocket(port);
System.out.println(“MultipleSocketServer Initialized”);
while (true)
{
Socket connection = socket1.accept();
Runnable runnable = new MultipleSocketServer(connection, ++count);
Thread thread = new Thread(runnable);
thread.start();
}
}
catch (Exception e) {}
}
MultipleSocketServer(Socket s, int i)
{
this.connection = s;
this.ID = i;
}
public void run()
{
try
{
BufferedInputStream is = new BufferedInputStream(connection.getInputStream());
InputStreamReader isr = new InputStreamReader(is);
int character;
StringBuffer process = new StringBuffer();
while((character = isr.read()) != 13)
{
process.append((char)character);
}
System.out.println(process);
//need to wait 10 seconds to pretend that we’re processing something
try
{
Thread.sleep(10000);
}
catch (Exception e){}
TimeStamp = new java.util.Date().toString();
String returnCode = “MultipleSocketServer repsonded at “+ TimeStamp + (char) 13;
BufferedOutputStream os = new BufferedOutputStream(connection.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(os, “US-ASCII”);
osw.write(returnCode);
osw.flush();
}
catch (Exception e)
{
System.out.println(e);
}
finally
{
try
{
connection.close();
}
catch (IOException e){}
}
}
}