Newer
Older
nonet / tp6-8 / src / ch / epfl / lca / sc250 / ServentClient.java
@Andreas Jaggi Andreas Jaggi on 12 Jun 2006 1 KB Changed directory structure
package ch.epfl.lca.sc250;

import ch.epfl.lca.sc250.gui.finalgui.*;

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

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

	/**
	 * Instance of the GUI
	 */
	CnFrameMain 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(CnFrameMain gui) {
		myGui = gui;
		// 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(new CnFrameMain("abc"));
	}

	/**
	 * 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");
		}

	}

}