-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTCPServer.java
55 lines (48 loc) · 2.37 KB
/
TCPServer.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
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String[] args) throws IOException {
// Variables for setting up connection and communication
Socket Socket = null; // socket to connect with ServerRouter
PrintWriter out = null; // for writing to ServerRouter
BufferedReader in = null; // for reading form ServerRouter
InetAddress addr = InetAddress.getLocalHost();
String host = addr.getHostAddress(); // Server machine's IP
String routerName = addr.getHostName(); // ServerRouter host name
int SockNum = 5555; // port number
// Tries to connect to the ServerRouter
try {
Socket = new Socket(routerName, SockNum);
out = new PrintWriter(Socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(Socket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about router: " + routerName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: " + routerName);
System.exit(1);
}
// Variables for message passing
String fromServer; // messages sent to ServerRouter
String fromClient; // messages received from ServerRouter
//IPV4 goes here
String address = "10.100.123.39"; // destination IP (Client)
// Communication process (initial sends/receives)
out.println(address);// initial send (IP of the destination Client)
fromClient = in.readLine();// initial receive from router (verification of connection)
System.out.println("ServerRouter: " + fromClient);
// Communication while loop
while ((fromClient = in.readLine()) != null) {
System.out.println("Client said: " + fromClient);
if (fromClient.equals("Bye.")) // exit statement
break;
fromServer = fromClient.toUpperCase(); // converting received message to upper case
System.out.println("Server said: " + fromServer);
out.println(fromServer); // sending the converted message back to the Client via ServerRouter
}
// closing connections
out.close();
in.close();
Socket.close();
}
}