-
Notifications
You must be signed in to change notification settings - Fork 0
/
EchoServer.java
75 lines (58 loc) · 2.16 KB
/
EchoServer.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
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.PrintStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.ServerSocket;
import java.util.*;
/*
* An echo server that simply echoes messages back.
*/
public class EchoServer {
// Create a socket for the server
private static ServerSocket serverSocket = null;
// Create a socket for the user
private static Socket connectionSocket = null;
private static BufferedReader inFromClient = null;
private static PrintStream outToClient = null;
public static void main(String args[]) throws Exception{
// The default port number.
int portNumber = 8000;
if (args.length < 1) {
System.out.println("Usage: java Server <portNumber>\n"
+ "Now using port number=" + portNumber + "\n");
} else {
portNumber = Integer.valueOf(args[0]).intValue();
}
/*
* Open a server socket on the portNumber (default 8000).
*/
//create welcoming socket at portNumber
ServerSocket serverSocket = new ServerSocket(portNumber);
/*
* Create a user socket for accepted connection
*/
while (true) {
try {
//wait, on welcoming socket for contact by client
connectionSocket = serverSocket.accept();
System.out.println("Accept client");
inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
outToClient = new PrintStream(connectionSocket.getOutputStream());
String clientSentence = inFromClient.readLine();
outToClient.print(clientSentence);
/*
* Close the output stream, close the input stream, close the socket.
*/
inFromClient.close();
outToClient.close();
connectionSocket.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}
}