-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClientHandler.java
147 lines (130 loc) · 2.51 KB
/
ClientHandler.java
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
/*
* This class will create a new thread to handle connections for all clients
*/
public class ClientHandler extends Thread
{
private static final String OBJECT_STR = "___Object___";
private static final String EXIT_STR = "LEAVE";
private AuctionServer server;
private Socket client;
private DataInputStream input;
private ObjectOutputStream outstream;
private Thread thread = null;
/*
* Constructor, creates Data and Object streams with the client
*/
public ClientHandler(Socket socket, AuctionServer server)
{
client = socket;
this.server = server;
try
{
input = new DataInputStream(new BufferedInputStream(client.getInputStream()));
}
catch (IOException ioEx)
{
// TODO: handle exception
ioEx.printStackTrace();
}
try
{
outstream = new ObjectOutputStream(client.getOutputStream());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* Waits for data from the client
*/
public void run()
{
thread = new Thread(this);
String msg;
while (thread != null)
{
try
{
msg = input.readUTF();
if (msg.equals(EXIT_STR))
{
server.leaveAuction(this);
thread = null;
}
else
{
server.newBid(msg, this);
}
}
catch (IOException ioEx)
{
// TODO Auto-generated catch block
ioEx.printStackTrace();
server.leaveAuction(this);
thread = null;
}
}
}
/*
* Closes connections to streams and sockets
*/
public void close() throws IOException
{
if (input != null)
{
input.close();
}
if (outstream != null)
{
outstream.close();
}
if (client != null)
{
client.close();
}
}
/*
* Uses ObjectOutputStream to send an AuctionItem to the client.
* First sends the String "___Object___" to allow client to process
*/
public void sendItem(AuctionItem item)
{
sendMsg(OBJECT_STR);
try
{
outstream.writeObject(item);
outstream.flush();
outstream.reset();
}
catch (IOException ioEx)
{
ioEx.printStackTrace();
server.leaveAuction(this);
thread = null;
}
}
/*
* Uses ObjectOutputStream to send a String to the client.
*/
public void sendMsg(String msg)
{
try
{
outstream.writeObject(msg);
outstream.flush();
outstream.reset();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}