Blame view

JChatServer/src/pad/prac2/MySocket.java 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package pad.prac2;

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

public class MySocket extends Socket
{
	private BufferedReader input;
	private OutputStream output;

	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 = super.getOutputStream();
			input = new BufferedReader(new InputStreamReader(super.getInputStream()));
		}
		catch(IOException ioExc)
		{
			System.out.println("TCP: Error initializing socket");
		}
	}

	public void sendMsg(String msg) throws IOException
	{
		String length = new Integer(msg.length()).toString();
		this.write(length + '\0' + msg);
	}

	public String recvMsg() throws IOException
	{
		String len,str;
		int length;
		len = this.readLine();
		if(len == "")
		{
			return len;
		}
		length = Integer.parseInt(len);
		str = this.read(length);
		return str;
	}

	public void write(String str) throws IOException
	{
		output.write(str.getBytes());
	}

	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() throws IOException
	{

		String line = "";
		char[] c = new char[1];
		while(true)
		{
			input.read(c,0,1);
			if(c[0] == '\0')
			{
				break;
			}
			line += c[0];
		}
		return line;
	}

	public void close()
	{
		try
		{
			super.shutdownInput();
			super.shutdownOutput();
			super.close();
		}
		catch(IOException ioExc)
		{
			System.out.println("TCP: Error while closing socket");
		}
	}
}