-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTCPClient.java
More file actions
62 lines (49 loc) · 2.38 KB
/
TCPClient.java
File metadata and controls
62 lines (49 loc) · 2.38 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
/*
* Java socket programming client example with TCP
* socket programming at the client side, which provides example of how to define client socket, how to send message to
* the server and get response from the server with DataInputStream and DataOutputStream
*
* */
import java.net.*;
import java.io.*;
public class TCPClient {
// server host and port number, which would be acquired from command line parameter
private static String serverHost;
private static Integer serverPort;
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.out.println("===== Error usage: java TCPClient SERVER_IP SERVER_PORT =====");
return;
}
serverHost = args[0];
serverPort = Integer.parseInt(args[1]);
// define socket for client
Socket clientSocket = new Socket(serverHost, serverPort);
// define DataInputStream instance which would be used to receive response from the server
// define DataOutputStream instance which would be used to send message to the server
DataInputStream dataInputStream = new DataInputStream(clientSocket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
// define a BufferedReader to get input from command line i.e., standard input from keyboard
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("===== Please input any message you want to send to the server: ");
// read input from command line
String message = reader.readLine();
// write message into dataOutputStream and send/flush to the server
dataOutputStream.writeUTF(message);
dataOutputStream.flush();
// receive the server response from dataInputStream
String responseMessage = (String) dataInputStream.readUTF();
System.out.println("[recv] " + responseMessage);
System.out.println("Do you want to continue(y/n) :");
String answer = reader.readLine();
if (answer.equals("n")) {
System.out.println("Good bye");
clientSocket.close();
dataOutputStream.close();
dataInputStream.close();
break;
}
}
}
}