This week's book giveaway is in the Other Languages forum.
We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!
See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to send a class instance via socket?

 
Chris Ben
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Chris Ben
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic