Summarize the Client
Our class is finished. Before we move on to the server side, let's review the steps to create and use the socket:
1. Instantiate the socket with the IP address and port of the machine you want to connect to (throw exception if there is a problem).
2. Get the stream on the socket to read and write.
3. Wrap the flow into a bufferedreader/printwriter instance, if it makes things simpler.
4. Read and write to the socket.
5. Close the open stream.
5 Creating a server socket
Create Remotefileserver Class
1.import java.io.*;
2.import java.net.*;
3.public class Remotefileserver {
4. int listenport;
5. Public remotefileserver (int listenport) {
6. This.listenport=listenport;
7. }
8. Allow the client to connect to the server and wait for the client to request
9. public void Acceptconnections () {
10. try {
11. ServerSocket Server = new ServerSocket (listenport);
12. Socket incomingconnection = null;
13. while (true) {
Incomingconnection = Server.accept ();
15. Handleconnection (incomingconnection);
16. }
17. }
18. catch (Bindexception e) {
19. System.out.println ("Unable to bind to port" +listenport);
20. }
21. catch (IOException e) {
22. System.out.println ("Unable to instantiate a serversocket on port:" +listenport);
23.
24. }
25. }
26. Interacts with the client socket to send the contents of the file requested by the client to the client
27. public void Handleconnection (Socket incomingconnection) {
28. try {
29. OutputStream outputtosocket = Incomingconnection.getoutputstream ();
30. InputStream inputfromsocket = Incomingconnection.getinputstream ();
BufferedReader streamReader = new BufferedReader (new InputStreamReader (Inputfromsocket));
32. FileReader FileReader = new FileReader (New File (StreamReader.ReadLine ()));
33. BufferedReader bufferedfilereader = new BufferedReader (FileReader);
34. PrintWriter StreamWriter = new PrintWriter (Incomingconnection.getoutputstream ());
35. String line = null;
36. while ((Line=bufferedfilereader.readline ())!=null) {
37. Streamwriter.println (line);
38. }
39. Filereader.close ();
40. StreamWriter.Close ();
41. Streamreader.close ();
42. }
43. catch (Exception e) {
44. System.out.println ("Error Handling a client:" +e);
E.printstacktrace ();
46. }
47. }
48. public static void Main (String args[]) {
49. Remotefileserver Server = new Remotefileserver (1001);
50. Server.acceptconnections ();
51. }
52.}