Newer
Older
nonet / src / ch / epfl / lca / sc250 / ServentClient.java
@Andreas Jaggi Andreas Jaggi on 4 May 2006 2 KB Completed exercice 2 of lab 7
package ch.epfl.lca.sc250;

import ch.epfl.lca.sc250.gui.CnFrameP2P;
import ch.epfl.lca.sc250.gui.ITCPSender;

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

/**
 * @author Christophe Trefois
 */
public class ServentClient implements ITCPSender {

	/**
	 * Instance of the GUI
	 */
	CnFrameP2P myGui;

	private Socket sock;
	private int targetport = 13371;
	private	BufferedReader inReader;
	private	DataOutputStream outStream;


	/**
	 * Constructor of the Client part of the Servent for 
	 * 
	 * @param windowTitle The title of the GUI
	 */
	public ServentClient(String windowTitle) {
		myGui = new CnFrameP2P(windowTitle);
		// Give the GUI an instance of the ServentClient
		myGui.setTcpSender(this);
	}

	/**
	 * Creates a new instance of ServentClient
	 * @param args
	 */
	public static void main(String[] args) {
		new ServentClient(" - Client of Servent - Computer Networking");
	}

	/**
	 * This method should open a TCP Socket and send the offer to the other player
	 */
	public void sendMessage(String ipAddress, String moneyAmount, String letterPosition) {
		// Open Communication to other Player and wait for a result
		// When result is recevied, display it in GUI

		System.out.println("Message sent to " + ipAddress + " : " + moneyAmount + ", " + letterPosition);
		
		// Opening Socket, Sending Request, Fetching answer
		try {
			sock = new Socket(ipAddress, targetport);

			outStream = new DataOutputStream(sock.getOutputStream());

			inReader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
		} catch ( UnknownHostException uhe ) {
			System.out.println("Unknown host");
		} catch ( IOException ioe ) {
			System.out.println("IO-Error");
		}

		try {
			outStream.writeBytes(moneyAmount + ", " + letterPosition + "\n");

			// Put the answer in String message = theAnswer;
			// Call this method to unblock the GUI
			String response = inReader.readLine();

			myGui.receivedMessage(response);
		} catch ( IOException ioe ) {
			System.out.println("IO-Error");
		}

	}

}