Help understanding Input/OutputStreams and BufferedReader/Writers by dissecting code
Here is the code that I wrote. First for the client:
Code :
import java.io.*;
import java.net.*;
public class ThenClient {
public static void main(String[] args) throws IOException {
int port = Integer.parseInt(args[0]);
String ipAddress = args[1];
InetAddress ia = InetAddress.getByName(ipAddress);
Socket client = new Socket(ia, port);
InputStream is = client.getInputStream();
OutputStream os = client.getOutputStream();
InputStreamReader isr = new InputStreamReader(is);
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedReader br = new BufferedReader(isr);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("Paul, you should make the internet in Morrison faster. Kthx!\n");
bw.flush();
System.out.println(br.readLine());
br.close();
bw.close();
osw.close();
isr.close();
os.close();
is.close();
client.close();
}
}
and then for the server:
Code :
import java.io.*;
import java.net.*;
public class ThenServer {
public static void main(String[] args) throws IOException {
int port = Integer.parseInt(args[0]);
String message = args[1];
ServerSocket server = new ServerSocket(port);
Socket client = server.accept();
InputStream is = client.getInputStream();
OutputStream os = client.getOutputStream();
InputStreamReader isr = new InputStreamReader(is);
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedReader br = new BufferedReader(isr);
BufferedWriter bw = new BufferedWriter(osw);
System.out.println(br.readLine());
bw.write(message + "\n");
bw.flush();
bw.close();
br.close();
osw.close();
isr.close();
os.close();
is.close();
client.close();
server.close();
}
}
I have read the APIs for all the classes I used but I don't understand what each line is doing exactly (apart from the closing ones). Our teacher gave us really guided directions to how to make this program which is why I was able to come up with the code but I have no experience with any network stuff so this is all really confusing to me. What the program is supposed to do is the server starts up with 2 command line arguments, a port and a message and then the client starts up with 2 command line arguments, a port and an ip address and then the client sends a static message to the server and the server responds back with the message entered in the command line. My program works, just wondering how it actually WORKS.
Thank you!
Re: Help understanding Input/OutputStreams and BufferedReader/Writers by dissecting c
What you say shows that you understand almost of the program. The server listens on a specific port. The client connects to the server using IP address that points to the server, and the port which is listened by the server. The client sends a message and the server responds back. That's all simple!