-
Notifications
You must be signed in to change notification settings - Fork 1
/
NodeJsEcho.java
42 lines (41 loc) · 2.15 KB
/
NodeJsEcho.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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class NodeJsEcho {
// socket object
private Socket socket = null;
public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException {
// class instance
NodeJsEcho client = new NodeJsEcho();
// socket tcp connection
String ip = "127.0.0.1";
int port = 8081;
client.socketConnect(ip, port);
// writes and receives the message
String message = "message123";
System.out.println("Sending: " + message);
String returnStr = client.echo(message);
System.out.println("Receiving: " + returnStr); }
// make the connection with the socket
private void socketConnect(String ip, int port) throws UnknownHostException, IOException {
System.out.println("[Connecting to socket...]");
this.socket = new Socket(ip, port); }
// writes and receives the full message int the socket (String)
public String echo(String message) {
try {
// out & in
PrintWriter out = new PrintWriter(getSocket().getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(getSocket().getInputStream()));
// writes str in the socket and read
out.println(message);
String returnStr = in .readLine();
return returnStr; }
catch (IOException e) { e.printStackTrace(); } return null; }
// get the socket instance
private Socket getSocket() {
return socket;
}
}