-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyServer.java
80 lines (68 loc) · 2.16 KB
/
myServer.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
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class myServer {
private static int port = 3339;
public static void main (String[] args) throws IOException {
ServerSocket serverSock = null;
//try to listen on the port specified above
try {
serverSock = new ServerSocket(port);
} catch (IOException portfail) {
System.err.println("Couldn't listen on port " + port);
System.err.println(portfail);
System.exit(1);
}
//try to accept a client connection
Socket clientSock = null;
while(true) {
try {
clientSock = serverSock.accept();
} catch (IOException acceptfail) {
System.err.println("Couldn't accept connection");
System.err.println(acceptfail);
System.exit(1);
}
System.out.println("accepted connection :)");
final Socket acceptedSock = clientSock;
//start a new thread to deal with this new client
Thread serverThread = new Thread(new Runnable() {
private Socket thisSock = acceptedSock;
private BufferedReader input = null;
@Override
public void run() {
//code run by thread ie server code once one client sock accepted
String msg;
System.out.println("in new thread");
Protocol pro = new Protocol(thisSock);
//make a new input stream reader and output writer to client
try {
input = new BufferedReader(new InputStreamReader(thisSock.getInputStream()));
new PrintWriter(thisSock.getOutputStream());
} catch (IOException streamerr) {
System.err.println("Failed to create input/output streams to client");
System.err.println(streamerr);
System.exit(1);
}
System.out.println("made the input/output streams");
while(thisSock.isClosed()==false) {
try {
if((msg = input.readLine()) != null) {
//process the client's message according to the protocol
pro.process(msg);
}
} catch (IOException readerr){
System.err.println("Error when reading input stream");
System.err.println(readerr);
System.exit(1);
}
}
}
});
serverThread.start();
}
}
}