-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTCPClient.java
57 lines (49 loc) · 1.25 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
// A Java program for a Client
import java.net.*;
import java.io.*;
public class TCPClient {
// initialize socket and input output streams
private Socket socket = null;
private BufferedReader input = null;
private DataOutputStream out = null;
// constructor to put ip address and port
public TCPClient(String address, int port) {
// establish a connection
try {
socket = new Socket(address, port);
System.out.println("Connected");
// takes input from terminal
input = new BufferedReader(new InputStreamReader(System.in));
// sends output to the socket
out = new DataOutputStream(socket.getOutputStream());
} catch(UnknownHostException u) {
System.out.println(u);
} catch(IOException i) {
System.out.println(i);
}
// string to read message from input
String line = "";
// keep reading until "Over" is input
while (!line.equals("Over")) {
try {
line = input.readLine();
out.writeUTF(line);
}
catch(IOException i) {
System.out.println(i);
}
}
// close the connection
try {
input.close();
out.close();
socket.close();
}
catch(IOException i) {
System.out.println(i);
}
}
public static void main(String args[]) {
TCPClient client = new TCPClient("127.0.0.1", 5000);
}
}