Blame view

JChatServerV2/src/pad/prac2/MySocket.java 2.04 KB
1
2
3
4
5
package pad.prac2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
6
import java.io.OutputStream;
7
8
9
10
11
12
13
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

public class MySocket extends Socket
{
	private BufferedReader input;
14
	private OutputStream output;
15
16
17
18

	public MySocket()
	{
		super();
19
20
21
22
23
	}

	public void connect(String host, int port)
	{
		SocketAddress addr = new InetSocketAddress(host,port);
24
25
		try
		{
26
27
			super.connect(addr);
			initializeStreams();
28
29
30
		}
		catch(IOException ioExc)
		{
31
			System.out.println("TCP: Error occured while connecting to remote host");
32
33
34
		}
	}
35
	public void initializeStreams()
36
37
38
	{
		try
		{
39
			output = super.getOutputStream();
40
			input = new BufferedReader(new InputStreamReader(super.getInputStream(),"UTF-8"));
41
42
43
		}
		catch(IOException ioExc)
		{
44
			System.out.println("TCP: Error initializing socket");
45
46
47
		}
	}
48
	public void sendMsg(String msg) throws IOException
49
50
	{
		String length = new Integer(msg.length()).toString();
51
		this.write(length + '\0' + msg);
52
53
	}
54
	public String recvMsg() throws IOException
55
56
57
58
	{
		String len,str;
		int length;
		len = this.readLine();
59
		if(len == "")
60
61
62
63
64
65
66
67
		{
			return len;
		}
		length = Integer.parseInt(len);
		str = this.read(length);
		return str;
	}
68
	public void write(String str) throws IOException
69
	{
70
		output.write(str.getBytes());
71
72
73
74
75
76
77
78
79
80
81
82
83
	}

	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");
84
85
86
87
			return null;
		}
	}
88
	public String readLine() throws IOException
89
	{
90
91
92
93

		String line = "";
		char[] c = new char[1];
		while(true)
94
		{
95
96
			input.read(c,0,1);
			if(c[0] == '\0')
97
			{
98
				break;
99
			}
100
101
102
103
104
105
106
107
108
109
110
111
			line += c[0];
		}
		return line;
	}

	public void close()
	{
		try
		{
			super.shutdownInput();
			super.shutdownOutput();
			super.close();
112
113
114
		}
		catch(IOException ioExc)
		{
115
			System.out.println("TCP: Error while closing socket");
116
117
118
		}
	}
}