source: java-rpg-common/Connection.java@ 04e7260

Last change on this file since 04e7260 was 04e7260, checked in by dportnoy <dmp1488@…>, 17 years ago

[svn r20]

  • Property mode set to 100644
File size: 2.9 KB
Line 
1import java.net.*;
2import java.io.*;
3
4public class Connection extends Thread {
5 private boolean connected;
6 private boolean interrupted;
7 private String ip;
8 private int port;
9 private Socket socket;
10 private PrintWriter out;
11 private BufferedReader in;
12
13 public Connection(String ip, int port, String threadName) {
14 super(threadName);
15
16 connected = false;
17 interrupted = false;
18 socket = null;
19 this.ip = ip;
20 this.port = port;
21 }
22
23 public Connection(Socket socket, String threadName) {
24 super(threadName);
25
26 connected = false;
27 interrupted = false;
28 this.socket = socket;
29 }
30
31 public static boolean isConnected(Connection obj) {
32 return obj != null && obj.connected;
33 }
34
35 protected PrintWriter getOut() {
36 return out;
37 }
38
39 protected BufferedReader getIn() {
40 return in;
41 }
42
43 public void interrupt() {
44 interrupted = true;
45 }
46
47 public void closeConnection() {
48 try {
49 if(connected) {
50 connected = false;
51 socket.close();
52 out.close();
53 in.close();
54 }
55 } catch(IOException ioe) {
56 ioe.printStackTrace();
57 }
58 }
59
60 protected void sendMessage(MessageType type, String input) {
61 out.println(type);
62 out.println(input);
63 }
64
65 protected void processMessage(MessageType type, String input) {
66
67 }
68
69 protected void connectionStart() {
70
71 }
72
73 protected void connectionSuccess() {
74
75 }
76
77 protected void connectionFailure() {
78
79 }
80
81 protected void connectionBreak() {
82
83 }
84
85 protected void peerDisconnect() {
86
87 }
88
89 protected void connectionEnd() {
90
91 }
92
93 public void run() {
94 String strType, str;
95
96 try {
97 connectionStart();
98 if(socket == null)
99 socket = new Socket(ip, port);
100 if(!interrupted) {
101 out = new PrintWriter(socket.getOutputStream(), true);
102 in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
103 connected = true;
104 connectionSuccess();
105 }
106 }catch (UnknownHostException uhe) {
107 if(!interrupted)
108 connectionFailure();
109 }catch (ConnectException ce) {
110 if(!interrupted)
111 connectionFailure();
112 }catch(IOException ioe) {
113 if(!interrupted)
114 ioe.printStackTrace();
115 }
116
117 if(interrupted)
118 closeConnection();
119
120 try{
121 while(connected && (strType = in.readLine()) != null && (str = in.readLine()) != null) {
122 processMessage(MessageType.valueOf(strType), str);
123 }
124 if(connected)
125 peerDisconnect();
126 }catch(SocketException se) {
127 if(connected)
128 connectionBreak();
129 }catch(IOException ioe) {
130 ioe.printStackTrace();
131 }
132
133 closeConnection();
134 connectionEnd();
135 }
136}
Note: See TracBrowser for help on using the repository browser.