Blame view

JChatServerV2/src/pad/prac2/MySocket.java 2.18 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
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
10
import java.nio.charset.Charset;
11
12
13
14

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

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

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

	public String read(int bytes)
	{
		char[] buffer = new char[bytes];
		try
		{
			input.read(buffer, 0, bytes);
80
81
			byte[] bytesRead = new String(buffer).getBytes("UTF-8"); //Cosas del Unicode, por culpa del **** Java
			return new String(bytesRead,"UTF-8");
82
83
84
85
		}
		catch(IOException ioExc)
		{
			System.out.println("TCP: Error retrieving data from remote endpoint");
86
87
88
89
			return null;
		}
	}
90
	public String readLine() throws IOException
91
	{
92
93
94
95

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

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