// Copyright MageLang Institute; Version $Id: //depot/main/src/edu/modules/Beans/magercises/SocketBean/Solution/sock/ClientSocket.java#3 $ package sock; import java.io.*; import java.net.*; import java.util.*; import java.awt.event.ActionEvent; public class ClientSocket implements Serializable { private Socket client; private DataInputStream in = null; private PrintStream out = null; private Vector targets = new Vector(); private int port = -1; // PROPERTY public void setPort(int p) { port = p; } public int getPort() { return port; } private String machine = "127.0.0.1"; // PROPERTY public void setMachine(String m) { machine = m; } public String getMachine() { return machine; } private String messageToWrite = "nothing for now"; // PROPERTY public void setMessageToWrite(String msg) { messageToWrite = msg; } public String getMessageToWrite() { return messageToWrite; } public synchronized void addSocketListener(SocketListener l) { targets.addElement(l); } public synchronized void removeSocketListener(SocketListener l) { targets.removeElement(l); } protected void notifyTargetsSent(String s) { Vector l; SocketEvent se = new SocketEvent(this, s); synchronized(this) { l = (Vector) targets.clone(); } for (int i = 0; i < l.size(); i++) { SocketListener sl = (SocketListener) l.elementAt(i); sl.sent(se); } } protected void notifyTargetsReceived(String r) { Vector l; SocketEvent se = new SocketEvent(this, r); synchronized(this) { l = (Vector) targets.clone(); } for (int i = 0; i < l.size(); i++) { SocketListener sl = (SocketListener) l.elementAt(i); sl.received(se); } } public void connect() throws IOException, UnknownHostException { if (port == -1) return; // do nothing if no port // connect to host at port client = new Socket(machine, port); out = new PrintStream(client.getOutputStream()); in = new DataInputStream(client.getInputStream()); } public void connectNoExceptions() { try { connect(); } catch (Exception e) { System.err.println("error connecting to socket: " + e.getMessage()); } } public void writeln(String s) { out.println(s); notifyTargetsSent(s); } public String readln() throws IOException { String r = in.readLine(); notifyTargetsReceived(r); return r; } public void writeToSocket() { out.println(messageToWrite); notifyTargetsSent(messageToWrite); } public void readFromSocket() { try { notifyTargetsReceived(in.readLine()); } catch (Exception e) { System.err.println("error reading from to socket: " + e.getMessage()); } } public void sayHello() { writeln("hello there Mr. Server"); } }