MySocket.java 2.18 KB
package pad.prac2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

public class MySocket extends Socket
{
	private PrintWriter output;
	private BufferedReader input;
	
	public MySocket()
	{
		super();
	}
	
	public void connect(String host, int port)
	{
		SocketAddress addr = new InetSocketAddress(host,port);
		try
		{
			super.connect(addr);
			initializeStreams();
		}
		catch(IOException ioExc)
		{
			System.out.println("TCP: Error occured while connecting to remote host");
		}
	}
	
	public void initializeStreams()
	{
		try
		{
			output = new PrintWriter(super.getOutputStream());
			input = new BufferedReader(new InputStreamReader(super.getInputStream()));
		}
		catch(IOException ioExc)
		{
			System.out.println("TCP: Error initializing socket");
		}
	}
	
	public void close()
	{
		try
		{
			super.shutdownInput();
			super.shutdownOutput();
			super.close();
		}
		catch(IOException ioExc)
		{
			System.out.println("TCP: Error while closing socket");
		}
	}
	
	public void sendMsg(String msg)
	{
		String length = new Integer(msg.length()).toString();
		this.write(length+'\0', length.length()+1);
		this.write(msg,msg.length());
	}
	
	public String recvMsg()
	{
		String len,str;
		int length;
		len = this.readLine();
		if(len == null)
		{
			return len;
		}
		length = Integer.parseInt(len);
		str = this.read(length);
		return str;
	}
	
	public void write(String str, int bytes)
	{
		output.print(str.substring(0,bytes));
	}
	
	public String read(int bytes)
	{
		char[] buffer = new char[bytes];
		try
		{
			input.read(buffer, 0, bytes);
			return new String(buffer);
		}
		catch(IOException ioExc)
		{
			System.out.println("TCP: Error retrieving data from remote endpoint");
			return null;
		}
	}
	
	public String readLine()
	{
		try
		{
			String line = "";
			char[] c = new char[1];
			while(true)
			{
				input.read(c,0,1);
				if(c[0] == '\0')
				{
					break;
				}
				line += c[0];
			}
			return line;
		}
		catch(IOException ioExc)
		{
			System.out.println("TCP: Error retrieving data from remote endpoint");
			return null;
		}
	}

}