-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtcpClient.java
79 lines (62 loc) · 1.46 KB
/
tcpClient.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
// tcpClient.java by fpont 3/2000
// usage : java tcpClient <server> <port>
// default port is 1500
import java.net.*;
import java.io.*;
public class tcpClient {
public static void main(String[] args) {
int port = 1500;
String server = "localhost";
Socket socket = null;
String lineToBeSent;
BufferedReader input;
PrintWriter output;
int ERROR = 1;
// read arguments
if(args.length == 2) {
server = args[0];
try {
port = Integer.parseInt(args[1]);
}
catch (Exception e) {
System.out.println("server port = 1500 (default)");
port = 1500;
}
}
// connect to server
try {
socket = new Socket(server, port);
System.out.println("Connected with server " +
socket.getInetAddress() +
":" + socket.getPort());
}
catch (UnknownHostException e) {
System.out.println(e);
System.exit(ERROR);
}
catch (IOException e) {
System.out.println(e);
System.exit(ERROR);
}
try {
input = new BufferedReader(new InputStreamReader(System.in));
output = new PrintWriter(socket.getOutputStream(),true);
// get user input and transmit it to server
while(true) {
lineToBeSent = input.readLine();
// stop if input line is "."
if(lineToBeSent.equals(".")) break;
output.println(lineToBeSent);
}
}
catch (IOException e) {
System.out.println(e);
}
try {
socket.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}