Here is the code that I wrote. First for the client:
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:
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!


LinkBack URL
About LinkBacks
Reply With Quote