forked from sparrowxiao/ConcurrentTest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHandleClient.java
More file actions
71 lines (63 loc) · 2.49 KB
/
HandleClient.java
File metadata and controls
71 lines (63 loc) · 2.49 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
import java.io.*;
import java.net.*;
import java.lang.*;
/**
*
* @author sparrow
*/
public class HandleClient extends Thread {
private Socket clientSocket = null;
private int clientNo = 0;
private OutputStreamWriter osw = null;
private InputStreamReader isr = null;
private BufferedReader br = null;
// constructor
public HandleClient( Socket socket, int clientNo) {
//super( "ServerThread");
this.clientSocket = socket;
this.clientNo = clientNo;
} // constructor
public void run() {
char request[] = new char[4];
int nChars =0;
try {
osw = new OutputStreamWriter( clientSocket.getOutputStream());
// the above line might need , "US-ASCII"); or // "UTF-8"?
System.out.println( "Connection from: " +
clientSocket.getInetAddress());
isr = new InputStreamReader( clientSocket.getInputStream()); // the above line might need , "US-ASCII"); or // "UTF-8"?
br = new BufferedReader( isr);
do
{
// try changing for isr rather than br
//request = br.readLine();
//System.out.println( "\tFrom client " + clientNo + ": " + request);
nChars = isr.read(request,0,request.length);
System.out.println("\t Reveived:"+ new String(request,0,nChars));
// What happens if we don't send '\r\n' or only one of them?
osw.write( "Hello from "+ InetAddress.getLocalHost() + " to Client no:" + clientNo + "\r\n");
osw.flush(); // make sure msg got sent from the buffer!
//} while( !request.equals( "END"));
System.out.print( "ClientNo is \n:" + clientNo);
} while( !(new String(request)).equals( "END"));
System.out.println( "Client " + clientNo + " closed connection");
osw.close();
isr.close();
br.close();
clientSocket.close();
} // end try{} accepting a client connection
catch( IOException ioE) {
System.err.println( "Connection error, maybe the client died!");
}
finally
{ // to trap any other errors!!
try {
if( clientSocket != null)
{
clientSocket.close();
}
}
catch( IOException ioE) {}
}
}
}