How to Upload Serilized Java File to Server
This series, The Object-Oriented Thought Process, is intended for someone simply learning an object-oriented language and who wants to sympathize the basic concepts before jumping into the code, or someone who wants to understand the infrastructure behind an object-oriented language he or she is already using. These concepts are function of the foundation that any developer will need to make the image shift from procedural programming to object-oriented programming.
Click here to starting time at the starting time of the series.
In keeping with the code examples used in the previous articles, Java will be the language used to implement the concepts in code. 1 of the reasons that I like to use Java is because you can download the Java compiler for personal use at the Sunday Microsystems Spider web site http://java.sun.com/. Yous can download the standard edition, J2SE 5.0, at http://java.sun.com/j2se/1.five.0/download.jsp to compile and execute these applications. I often reference the Java J2SE v.0 API documentation and I recommend that y'all explore the Java API further. Code listings are provided for all examples in this article as well as figures and output (when appropriate). See the kickoff article in this series for detailed descriptions for compiling and running all the code examples.
In the previous column, you covered several advanced techniques about connecting to a database using Java Database Connectivity (JDBC). Storing information to a database is just 1 of many ways to save data—a concept called data persistence. In this commodity, you will explore some other aspect of object persistence/serialization, specifically how practise yous motion an object across a customer-server connection? You may desire to store an object on a automobile that is continued to your application via a network connection. You will create a very simple customer/server application and transfer an object from the client to the server and dorsum.
Designing the Employee Class
Before you delve into the code to implement the client/server application, you must design a grade to be sent across the customer/server wire. In short, you will instantiate an object that volition exist marshaled between the client and the server. Remember that when y'all say marshaled you mean moving the object betwixt two points. Specifically, the object must exist decomposed into a form that can be transported beyond a wire so rebuilt on the opposite side of the wire.
In this example, you lot create a class called Employee. The employee is built from the following specifications:
Ii attributes:
- private int employeeNumber;
- private Cord employeeName;
Constructor (set the attributes):
- Employee(int num, String name)
Methods (getters and setters for the attributes):
- public int getEmployeeNumber()
- public void setEmployeeNumber(int num)
- public String getEmployeeName()
- public void setEmployeeName(String name)
This class is not going to do a whole lot. It is really only here and then you have something to send across the network. What yous desire to practice with your client/server arrangement is this:
- Instantiate objects of type Employee
- Set the attributes to some values
- Send the object from the client to the server
- Take the server change some of the values
- Transport the object from the server dorsum to the customer
- Verify that the client has the updated information
The complete code for this simple Employee class is shown in Listing ane.
import java.io.*; import java.util.*; public grade Employee implements Serializable { private int employeeNumber; private Cord employeeName; Employee(int num, String name) { employeeNumber = num; employeeName= name; } public int getEmployeeNumber() { return employeeNumber ; } public void setEmployeeNumber(int num) { employeeNumber = num; } public String getEmployeeName() { render employeeName ; } public void setEmployeeName(String proper name) { employeeName = name; } } List 1: The Employee Object
An important point worthy of involvement here is the way the grade is defined:
public class Employee implements Serializable
Note the utilise of the keyword Serializable. This interface identifies that the class can exist serialized. The Serializable interface does not actually contain whatsoever methods; it is used as a sort of tag that marks the class as Serializable. In the words of the Java two API specification: "The serialization interface has no methods or fields and serves only to place the semantics of being Serializable." At this signal, this is all you lot need to know about serialization; nevertheless, y'all will investigate some interesting problems that pertain to Serializable in a hereafter commodity.
The sole purpose of the Employee class is to comprise the employeeNumber and employeeName. Thus, yous can create an case of this grade to demonstrate the specifics of sending it across a client/server network. These attributes, along with their getters/setters, are all you need for this purpose.
The Client
You will first take a wait at the Client end of the arrangement. You could just every bit easily start by developing the Server. In this organisation, the Client will practise the piece of work of creating the Employee object. Thus, it makes sense to kickoff with the Client.
Here are the steps needed to properly demonstrate the features of your client.
- Create an Employee object
- Echo the Employee information to confirm the initial values
- Create a socket
- Create an ObjectOutputStream
- Create an InputOutputStream
- Write the Employee object to the ObjectOutputStream
- This where the object is sent to the Server
- Retrieve the updated Employee object from the InputOutputStream
- Later on the Server changes it
- Repeat the Employee data to verify the change in values
- Shut the ObjectOutputStream
- Shut the InputOutputStream
Creating the Employee Object
The instantiation of the Employee object is the simplest part of the procedure. To make things equally clean as possible, you create a single object so you don't have to worry most any synchronization. The complete Client.java file can be seen in List 2.
For this specific example, you create an Employee object chosen joe.
Employee joe = new Employee(150, "Joe");
Make sure that the Customer.java file is in the same directory every bit the Employee.coffee file. If you lot decide to use packages, you will take to brand sure that your import statements reflect this. You volition keep things uncomplicated and apply the default packaging.
Using the parameters passed to the constructor, the object joe now has an employeeNumber of 150 and an employeeName of "Joe". This is the object that you will send from the Client application to the Server. Annotation that both the Customer and the Server are separate applications and thus they both have a main() method. To get the client/server system upwardly and running, y'all volition have to create a procedure for both.
Before you start looking at the networking code, the Client kickoff echoes the values of the new joe object, just so you experience confident that the object was created properly.
System.out.println("employeeNumber= " + joe .getEmployeeNumber()); System.out.println("employeeName= " + joe .getEmployeeName()); Creating the Socket
The first function in connecting to the network is to create a socket using the Socket grade. The SDK documentation describes a socket as "an endpoint for communication betwixt ii machines".
To use the Socket course, you must import the coffee.net bundle.
import java.net.*;
you create an object called socketConnection using the Socket class. The single line of lawmaking is as follows.
Socket socketConnection = new Socket ("127.0.0.i", 11111); This version of the Socket constructor creates a stream socket and connects it to the specified port (11111) number at the specified IP address ("127.0.0.1"). The SDK API states, "y'all can specify a port number, or 0 to apply any free port".
Even though there is non much code needed to create a Socket, two of import parameters are passed to the Socket constructor. The first parameter is the URL (actually class InetAddress) of the Server you intend to connect to. This is a String, and the specific URL used here is called a loop-dorsum. The loop-back URL ("127.0.0.1") literally points to the same auto. This is a great technique for testing. With this feature, you lot can create the Client and the Server on the same machine so that you do not demand to accept an agile network connection to test your applications.
In the next column, I will provide a different URL so that you tin can test this system over the Internet. In whatsoever event, having the selection to test the system on a single machine really makes development a lot easier.
The second parameter is an integer and represents a virtual socket that you will associate with this specific client/server application. There is some flexibility with this number; you tin can vary information technology. Nonetheless, the Client and the Server must use the same socket number for this system to piece of work properly.
Creating the ObjectStreams
Subsequently the socket connectedness is fabricated, you need to create a couple of object streams, at least in this case. Again, you will keep it simple so yous don't accept to worry nearly synchronization. You create an ObjectOutputStream, called clientOutputStream. This allows the Client to write the Employee object to clientOutputStream.
Taking a look at the Lord's day documentation regarding the ObjectOutputStream is helpful: "an ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects tin can exist read (reconstituted) using an ObjectInputStream. Persistent storage of objects tin can be achieved by using a file for the stream. If the stream is a network socket stream, the objects tin can exist reconstituted on another host or in another process".
In essence, you are stuffing the Employee object, in this example joe, into a "pipe" that is connected to a server (that you will construct adjacent). Offset, you need to acquaintance the object streams with the socketConnection object y'all created earlier. The lawmaking for this is as follows.
ObjectOutputStream clientOutputStream = new ObjectOutputStream(socketConnection.getOutputStream()); ObjectInputStream clientInputStream = new ObjectInputStream(socketConnection.getInputStream());
This is a good case of a Coffee filter. Java I/O uses filters extensively and this is one of those places. By associating the object streams with the socket you created, actual socket information is "filtered" and, in effect, hidden from you. All you have to exercise from at present on is to read and write to and from the object streams; we don't take to worry nigh the socket. This keeps y'all focused on the layer that you collaborate with directly. It also allows you to change things like the URL and virtual socket without forcing you to modify a lot of lawmaking.
Writing the Employee Object to the Network
One time the object streams are created, you tin write the Employee object joe to the network. This is accomplished with the following line of code.
clientOutputStream.writeObject(joe);
Observe how simple this code is. All you lot are doing is using the writeObject() method of the OutputStream course with joe every bit a parameter. You don't take to worry about the socket, the URL, or annihilation about the network connection. The SDK API states that "the writeObject() method is responsible for writing the state of the object for its detail grade so that the corresponding readObject() method tin can restore information technology".
At this point, the joe object is loaded into the "pipe" that connects the Client to the Server. If the Server connectedness is not present, an exception will be generated. In fact, if the Server is not running, exceptions will be generated earlier in the process; you will explore many of these exception conditions.
The joe object is now "pipe" and ready to be retrieved by the Server, which volition read it, update it, and then send it back. Once the Server is done with it, the Client can take the object back off the "pipe."
Retrieving the updated Employee Object from the Network
Remember that this application was designed with simplicity in heed. Thus, once the Client sends the joe object to the Server, it simply waits for the object to come back. This is achieved past using the following line of lawmaking.
joe= (Employee)clientInputStream.readObject();
Yous are using 2 dissever object streams to exercise the job. The Customer and the Server will share the connections (pipes). Plainly, the output stream for the client volition exist the input stream for the Server and visa versa. Thus, the Client volition put the initial joe object on its output stream. The Server then will take that object off its input stream.
The SDK API states that "the method readObject() of the input stream is used to read an object from the stream. Java's safe casting should be used to get the desired type." In Java, strings and arrays are objects and are treated as objects during serialization. When read, they need to exist cast to the expected type.
Later on altering the joe object, the Server puts joe in its output stream. So, the Client retrieves joe from its input stream. This may seem disruptive at get-go; notwithstanding, in one case you run the lawmaking it volition become clearer. You can retrieve of it as a ii-lane highway from i urban center to another. There is an eastbound and a westbound side—and each can only become in one direction.
Once the Client retrieves the joe object, you print out the attributes of the object so that you tin verify that the Server actually did get possession of the object and contradistinct the attributes employeeNumber and employeeName.
Organisation.out.println("employeeNumber= " + joe .getEmployeeNumber()); System.out.println("employeeName= " + joe .getEmployeeName()); Closing the Object Streams
Finally, you need to do some housekeeping. In this case, you will close both the input and output streams with the post-obit lines.
clientOutputStream.close(); clientInputStream.shut();
This completes the code for the Client. The only other consequence that yous should pay attention to is that the code in the Customer is incorporated inside a try/catch block. This is required for compilation. Every bit stated earlier, I volition embrace the various exceptions and how we handle them in afterward articles. Listing 2 contains the complete code for the Client.
import java.io.*; import java.net.*; public class Customer { public static void main(String[] arg) { attempt { Employee joe = new Employee(150, "Joe"); Arrangement.out.println("employeeNumber= " + joe .getEmployeeNumber()); Arrangement.out.println("employeeName= " + joe .getEmployeeName()); Socket socketConnection = new Socket("127.0.0.1", 11111); ObjectOutputStream clientOutputStream = new ObjectOutputStream(socketConnection.getOutputStream()); ObjectInputStream clientInputStream = new ObjectInputStream(socketConnection.getInputStream()); clientOutputStream.writeObject(joe); joe= (Employee)clientInputStream.readObject(); System.out.println("employeeNumber= " + joe .getEmployeeNumber()); System.out.println("employeeName= " + joe .getEmployeeName()); clientOutputStream.close(); clientInputStream.close(); } catch (Exception e) {System.out.println(e); } } } Listing two: The Customer
The Server
With the Client lawmaking complete, you lot at present turn your attention to the Server. For obvious reasons, the Client cannot function without the Server. And so, before you can demonstrate the Client code, you have to go the Server up and running. Information technology is something like the craven and egg dilemma—which comes first, the Client or the Server? In reality, you need both for the system to work. Notwithstanding, 1 thing is for certain; the Server must be started before you can procedure whatsoever Client activities. In fact, the Server tin handle multiple Clients, a scenario that you volition investigate later on.
Here are the steps that demand to exist completed to properly create the Server.
- Create a reference to the Employee object
- Create a server socket connectedness
- Create a socket to accept an object from the "pipage"
- Create an ObjectOutputStream
- Create an InputOutputStream
- Read an Employee object
- Alter the Employee number
- Change the Employee name
- Write the revised employee object to the output stream
- Close the object streams
Remember that in this organization, the Server never actually instantiates an Employee object. It uses the ane sent to information technology by the Client.
Create a Reference to the Employee Object
In the Server, you lot are going to apply an Employee object sent from the Customer. To do this, the Server must create a reference to an Employee object. When the object is received from the Client, the reference then "points" to that object. The following lawmaking created the reference.
Employee employee = zip;
At the time this reference is defined, y'all fix it to nil.
Creating the Socket
In that location are really two steps to creating the Socket connection for the Server. First, you create an case of the class ServerSocket.
The SKD API states, "this grade implements server sockets. A server socket waits for requests to come up in over the network and then creates a server socket, bound to the specified port."
ServerSocket socketConnection = new ServerSocket(11111);
The difference here is that y'all do non have to specify a URL, only the virtual socket. In the Customer case, you needed to "locate" the Server by using the URL. In the case of the Server, you will read the object directly off the virtual port. The port number must be the same for the Server and the Customer.
Once the connection to the virtual port is in place, the Server volition await for an object to "bear witness up" at the port. Before you look, yous write a bulletin to the console indicating the Server is up and running.
Organization.out.println("Server Waiting"); However, it is not the connection to the virtual port that initiates the "Waiting" state. The following line of code accomplishes that task.
Socket pipe = socketConnection.accept();
According to the SDK API, "the accept() method listens for a connectedness to be fabricated to this socket and accepts it. The method blocks until a connection is made."
You create a Socket object that you phone call pipe. Using the accept() method, y'all now simply wait for something to announced at the virtual socket. That something is the object sent from the Customer.
Creating the ObjectStreams
As with the Client, you create ii object streams, one for the input and one for output. These are the complements of the streams created in the Client. The output stream of the Customer connects to the input stream of the Server and visa versa.
ObjectInputStream serverInputStream = new ObjectInputStream(pipe.getInputStream()); ObjectOutputStream serverOutputStream = new ObjectOutputStream(pipe.getOutputStream());
Reading the Employee Object and Writing it Back
At present, the infrastructure is in identify to read the Employee object off of the "piping." One time you execute the accept() method, the Server will wait until it is notified that an object is gear up to exist read. When this happens, the Server continues and the post-obit lawmaking is executed.
employee = (Employee )serverInputStream.readObject();
You employ the readObject() method to read the object off of the "pipe." This method returns the reference to the Employee object that was sent from the Client. You use the reference that was created earlier. Notation that you cast the object to the reference. The readObject() method returns an Object off the "piping;" yous must bandage it to the specific object that yous want.
One time you retrieve the Employee object from the connection, you can make a couple of simple changes. you do this and so that when yous send it back to the Customer, you can verify that the Server actually inverse information technology.
employee .setEmployeeNumber(256); employee .setEmployeeName("John"); Afterward you lot change the object, you transport it back to the Customer using the output stream with the following code:
serverOutputStream.writeObject(employee);
Closing the Object Streams
Finally, yous need to do some housekeeping. In this case, you volition close both the input and output streams with the following lines.
serverOutputStream.shut(); serverInputStream.close();
This completes the code for the Server. As with the Client, the code in the Server is incorporated inside a endeavor/catch block. This is required for compilation. Every bit stated earlier, you will embrace the various exceptions and how to handle them in later articles. List 3 contains the consummate code for the Server.
import java.io.*; import java.net.*; public class Server { public static void main(Cord[] arg) { Employee employee = null; try { ServerSocket socketConnection = new ServerSocket(11111); System.out.println("Server Waiting"); Socket piping = socketConnection.accept(); ObjectInputStream serverInputStream = new ObjectInputStream(pipage.getInputStream()); ObjectOutputStream serverOutputStream = new ObjectOutputStream(pipe.getOutputStream()); employee = (Employee )serverInputStream.readObject(); employee .setEmployeeNumber(256); employee .setEmployeeName("John"); serverOutputStream.writeObject(employee); serverInputStream.close(); serverOutputStream.close(); } catch(Exception e) {System.out.println(e); } } } Listing 3: The Server
Running the System
In this article, you lot simply set upward the infrastructure for a working Client/Server model. There are many fascinating points that you volition explore in time to come articles. However, you should get this basic model up and running so that you can verify that the organisation is in working guild.
Compiling the Lawmaking
I compile the code using a DOS Shell. Eventually, you will need two of these DOS Shells—ane to run the Server and one for the Client. Y'all can open a DOS Vanquish in the Programs->Accessories option.
Type the following lawmaking at the command prompt to compile all three of the files.
"C:Program FilesJavajdk1.v.0_06binjavac" Employee.coffee "C:Program FilesJavajdk1.5.0_06binjavac" Client.java "C:Plan FilesJavajdk1.5.0_06binjavac" Server.java
Figure 1 shows the screen shot of how this is accomplished.
Figure 1: Compiling the Code
Starting the Server
In ane of the DOS Shells, type in the post-obit line at the command prompt.
"C:Program FilesJavajdk1.5.0_06binjava" Server
Figure 2 shows what happens in the DOS Trounce.
Figure 2: Starting the Server
If everything is working properly, the "Server Waiting" message is displayed. At this point, you tin can start the Client.
Starting the Client
In a separate DOS Trounce, beginning the Client with the following line:
"C:Program FilesJavajdk1.5.0_06binjava" Client
The issue is shown in Figure three.
Figure three: Starting the Customer
If all is well, yous will see that the employeeNumber and the employeeName both were changed. You tin can put some specific identification in the print statements to provide further balls.
With the circuit consummate, the Server should exit cleanly, every bit shown in Figure iv.
Figure 4: Completing the Organisation
Decision
In this article, you covered the bones concepts involved with creating a simple Customer/Server model. The code is a complete and functional model. There are many interesting aspects of Client/Server models that you have yet to explore.
Moving an object from one place to another is ofttimes a tricky proposition. Using modern object-oriented languages makes life a lot easier for today's programmers. Information technology is very interesting to look at code from earlier programming languages pertaining to network programming. In years past, basic network programming required the developer to develop code that was sometimes quite circuitous or purchase 3rd-party software that was often hard to apply. Languages such every bit Java and .Internet have much of this functionality built correct into the language.
As stated before, although the example of this article is complete and useful, information technology is quite basic. There are many more fascinating topics to explore regarding customer/server applications. Next calendar month, y'all will investigate several of these interesting topics.
References
Tyma, Paul, Gabriel Torok and Troy Downing: Java Primer Plus. The Waite Group, 1996.
www.javasoft.com
Virtually the Author
Matt Weisfeld is a faculty member at Cuyahoga Community College (Tri-C) in Cleveland, Ohio. Matt is a member of the It department, teaching programming languages such as C++, Coffee, and C# .NET as well as various web technologies. Prior to joining Tri-C, Matt spent 20 years in the information technology manufacture gaining experience in software development, project management, business development, corporate training, and function-time education. Matt holds an MS in computer science and an MBA in project management. Besides The Object-Oriented Thought Process
, which is now in information technology'south second edition, Matt has published two other computer books, and more a dozen manufactures in magazines and journals such equally Dr. Dobb'south Journal, The C/C++ Users Journal, Software Development Magazine, Coffee Report, and the international periodical Project Management. Matt has presented at conferences throughout the Usa and Canada.
Source: https://www.developer.com/design/serializing-an-object-via-a-client-server-connection/
0 Response to "How to Upload Serilized Java File to Server"
Post a Comment