forked from TimSongCoder/LearnJavaForAndroid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEchoClient.java
More file actions
45 lines (42 loc) · 1.25 KB
/
Copy pathEchoClient.java
File metadata and controls
45 lines (42 loc) · 1.25 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
import java.net.Socket;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
public class EchoClient{
public static void main(String[] args){
if(args.length!=1){
System.err.println("usage: java EchoClient message");
System.err.println("example: java EchoClient I love New York");
return;
}
String message = args[0];
System.out.println("Sending message...");
Socket socket = null;
try{
socket = new Socket("localhost", EchoServer.ECHO_SERVER_PORT);
// explore the ports.
System.out.println("LocalPort: " + socket.getLocalPort() + ", RemotePort: " + socket.getPort());
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.println(message);
pw.flush();
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String messageBack = br.readLine(); // without line feed.
System.out.println("EchoBack: " + messageBack);
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
if(socket!=null){
try{
socket.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
}
}
}