aspose file tools
The moose likes Beginning Java and the fly likes How to send a class instance via socket? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "How to send a class instance via socket?" Watch "How to send a class instance via socket?" New topic
Author

How to send a class instance via socket?

Chris Ben
Ranch Hand

Joined: Jan 15, 2001
Posts: 135
Hi,
I am not quite familiar with ObjectInput and OutputStream? Can someone post an example showing how to send an object via socket from server to client?
Thank you for your help.
Chris
matt hooker
Ranch Hand

Joined: Jul 26, 2001
Posts: 46
Originally posted by Chris Ben:
Hi,
I am not quite familiar with ObjectInput and OutputStream? Can someone post an example showing how to send an object via socket from server to client?
Thank you for your help.
Chris

Hi Chris,
try something like :
try
{
socket = new Socket(host_name, port_number);
out = new PrintWriter(new BufferedWriter(new ObjectOutputStream(socket.getOutputStream())), true);
out.write(your_object);
}
catch (IOException io_ex)
{
System.err.println("Failed to create socket, " + host + ":" + port);
socket = null;
}
Matt.
p.s I will send a better (tested example) if you can't get something like this to work. Good Luck.

Its not what you do, its the way you say you've done it.
Chris Ben
Ranch Hand

Joined: Jan 15, 2001
Posts: 135
Thank you for your help.
I tried the polish the code, but I am stuck as the error below. My construct of socket failed to write out a object. And I even have no chance to try the server side.
Any suggestions?
Thanks a lot
Chris

import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception
{
myVector v=new myVector();
String host="localhost";
int port=6780;
Socket clientSocket=null;
PrintWriter outToServer=null;
try
{
clientSocket = new Socket("localhost", 6780);
outToServer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new ObjectOutputStream(clientSocket.getOutputStream()))), true);
outToServer.write(v);
}
catch (IOException io_ex)
{
System.err.println("Failed to create socket, " + host + ":" + port);
clientSocket = null;
}
clientSocket.close();
}
}

import java.io.*;
import java.util.Vector;
class myVector implements Serializable{
...
}
Error:
symbol : method write (myVector)
location: class java.io.PrintWriter
outToServer.write(v);
^
1 error
Tool completed with exit code 1
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: How to send a class instance via socket?
 
Similar Threads
Method serialization
Sending an image on network..
Update a program input after running
Reading an object from ObjectInputStream
How to connect YahooMessenger using socket connection?