Re: Java serialization over network
On Apr 2, 6:49 am, elbaid <elbaid_...@hotmail.com> wrote:
Just want to know if there's a tutorial or an how-to for serializing
object, put it in a stream over network, and deserialize it on the
other point. I understand the principles of serialization, I/O,
streams, sockets and so on, just want an example (client sending object
to a server) to start with.
Thank you.
---------------------------------------------------------------------------=
--
1. Example class to be serialized.
public class RuleInfo implements Serializable
{
private String data="";
public RuleInfo() {
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
2. User servlet to serialize...
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
RuleInfo info = new RuleInfo();
info.setData("1");
RuleInfo info1 = new RuleInfo();
info1.setData("2");
List<RuleInfo> list = new ArrayList<RuleInfo>();
list.add(info);
list.add(info1);
ObjectOutputStream out1 = new ObjectOutputStream
(response.getOutputStream());
out1.writeObject(list);
out1.flush();
out1.close();
System.out.println("This is done");
} finally {
}
}
3. Get Serialized Object at another place using ..
public void test() throws ClassNotFoundException
{
String urlString = "http://localhost:8084/WebApplication1/
BinaryPkgServlet";
try
{
InputStream stream = null;
URL url = new URL(urlString);
HttpURLConnection httpURLConnection = (HttpURLConnection)
url.openConnection();
/**
* If Response Code is 200 [OK] then get InputStream of
* Compiled binary Package remotely and store in local
file
* system.
*/
int httpResponseCode = httpURLConnection.getResponseCode
();
if (httpResponseCode == 200)
{
stream = httpURLConnection.getInputStream();
ObjectInputStream st = new ObjectInputStream(stream);
List<RuleInfo> list = (List<RuleInfo>)st.readObject();
System.out.println("List "+list +"and size "+list.size
());
for(RuleInfo info : list){
System.out.println("Info "+info.getData());
}
}
}
catch (IOException e)
{
}
}
Thanks,
Nilshan.