-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.java
More file actions
74 lines (65 loc) · 1.98 KB
/
Copy pathClient.java
File metadata and controls
74 lines (65 loc) · 1.98 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
72
73
74
import java.io.*;
import java.net.*;
import java.util.*;
// Client class
class Client {
private String serverAddress = "localhost";
private int serverPort = 3333;
private Socket socket;
private PrintWriter out;
private BufferedReader in;
private Scanner sc;
Client(String serverAddress,int serverPort)
{
setServerAddress(serverAddress);
setServerPort(serverPort);
}
public void runTCP()
{
try {
// establish a connection by providing host and port
// number
socket = new Socket(serverAddress, serverPort);
out = new PrintWriter(socket.getOutputStream(), true); // writing to server
in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // reading from server
sc = new Scanner(System.in);
String line = null;
while (!"exit".equalsIgnoreCase(line)) {
// reading from user
line = sc.nextLine();
// sending the user input to server
out.println(line);
out.flush();
// displaying server reply
System.out.println("Server replied " + in.readLine());
}
closeEverything();
} catch (UnknownHostException ex) {
throw new RuntimeException(ex);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public void closeEverything()
{
try {
// closing the scanner object
sc.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void setServerAddress(String serverAddress)
{
this.serverAddress = serverAddress;
}
public void setServerPort(int serverPort)
{
this.serverPort = serverPort;
}
public static void main(String[] args)
{
Client client = new Client("localhost",3333);
client.runTCP();
}
}