# [java] Java and Sockets

This topic is 4175 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Basically I would like to create applications that comunicate by using sockets. I would like to know how I to send an object instead of a text message as those shown in sun tutorials by using sockets ? Cheers !!

##### Share on other sites
If you're using a PrintWriter to send the data it has a print method which allows objects as a parameter.

##### Share on other sites
actually, i saw this method, but i didn't tested it because i don't know how the reciever would decode it...

##### Share on other sites
DISCLAIMER: I haven't done this in a long time so I could be off a bit

if you're using a BufferedReader you could use the read() method of it and make it like

##### Share on other sites
here is the way i read the recieved message :

while ((inputLine = in.readLine()) != null)
{
recieved.setText(inputLine);
if (inputLine.equals("Bye."))
break;
}

##### Share on other sites
here is the way I was used to sending the text message.

out.println(sendtext.getText());

##### Share on other sites
Yet another disclamier from me, but shouldnt you be able to wrap the input/output streams of the socket in ObjectInputStream and ObjectOutputStreams ?

Something like
Socket socket = getSocket();ObjectInputStream objectsIn = new ObjectInputStream( socket.getInputStream() );ObjectOutputStream objectsOut = new ObjectOutputStream( socket.getOutputStream() );objectsOut.writeObject( someObject ); // should appear at other end...?

The Objects you send might have to be serializable or something, my java is a bit rusty...

##### Share on other sites
I'm quite new in Java. What do you mean by "serializable "? Indeed I have met this word lots of time, but I have never got its meaning...

##### Share on other sites
Quote:
 Original post by jolyqrI'm quite new in Java. What do you mean by "serializable "? Indeed I have met this word lots of time, but I have never got its meaning...

If the class implements the interface Serializable then it can be written using ObjectInputStreams to various input streams ( network sockets, files, etc ) and can be retrieved via ObjectOutputStreams. Thats what I remember anyway...

##### Share on other sites
Yes, a class that implements the java.io.Serializable interfaced can be serialized and sent through a stream of bytes. The ObjectInputStream is used to read Objects from a stream, while the ObjectOutputStream is the counterpart, used to write them. Any property declared with the keyword "transient" in the Serializable class is not considered for serialization. RMI - Remote Method Invocation - uses this concept to serve Remote Objects for the applications' clients.

I must remind you that serialization and de-serialization is an expensive operation; beware on how you use it, and for what you use it. You can always encapsulate data into datagrams, or even better, into NIO's ByteBuffer instances, and use asynchronous communication for maximum performance.

Son Of Cain

##### Share on other sites
Quote:
 Original post by Son of CainYes, a class that implements the java.io.Serializable interfaced can be serialized and sent through a stream of bytes. The ObjectInputStream is used to read Objects from a stream, while the ObjectOutputStream is the counterpart, used to write them. Any property declared with the keyword "transient" in the Serializable class is not considered for serialization. RMI - Remote Method Invocation - uses this concept to serve Remote Objects for the applications' clients.I must remind you that serialization and de-serialization is an expensive operation; beware on how you use it, and for what you use it. You can always encapsulate data into datagrams, or even better, into NIO's ByteBuffer instances, and use asynchronous communication for maximum performance.Son Of Cain

Could you tell me more about the last concepts?
I know that UDP protocol uses datagrams for sending data...

##### Share on other sites
Quote:
 Original post by rip-offYet another disclamier from me, but shouldnt you be able to wrap the input/output streams of the socket in ObjectInputStream and ObjectOutputStreams ?Something like*** Source Snippet Removed ***The Objects you send might have to be serializable or something, my java is a bit rusty...

actually i do not know, that's why i'm here...
i'm looking for samples explaining how to use these commands as well

##### Share on other sites
Quote:
 Original post by jolyqrCould you tell me more about the last concepts?

Certainly. Although I mentioned NIO, I suggest you to try out something more simpler first; NIO is quite complex if you're still green on networking with Java. After a couple of tries, though, you can create incredible applications with it.

So i'll give a simple example of the mentioned wrapper classes. I assume you already know how to open a socket connection using standard Java IO, right?

Ok. Whatever you're trying to send on a stream, must implement Serializable:
public interface NetworkCommand extends java.io.Serializable {}

Then, you have that basic command of yours:
public class BasicCommand implements NetworkCommand {    // These attributes won't be sent to the stream (serialized)  private transient Object localCopyOfObject;  private static transient int count = 0;  private int order;  private String command;    // ...}

Your Socket instance has two methods: getInputStream() and getOutputStream(). These streams are the very streams used to read and write data using the stream connection opened with your server. We create wrappers on these streams, that is, ObjectInput/OutputStream instances that use these streams to read and write objects using them:
Socket socket;ObjectInputStream ois = new ObjectInputStream( socket.getInputStream() );ObjectOutputStream oos = new ObjectOutputStream( socket.getOutputStream() );// These methods block while reading/writting data, so you better put them in their own threadsois.readObject();oos.writeObject(new BasicCommand());

That's it... basically, you open a connection using a Socket, and then wrap the resulting streams using these classes. You write and read your network commands using them, easy as that.

A fairly simple example:
public class NetworkInputHandler implements Runnable {    private Socket socket;  private boolean running;  private Queue < NetworkCommand > commands;  public NetworkHandler(Socket s) {    this.socket = s;    running = true;  }    public void run() {    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());    while ( running ) {      Object input = ois.readObject();            // process object and put it into queue      // ...    }  }  }

Son Of Cain

##### Share on other sites
It works without any problem when i'm sending strings, but i've got some difficulties when it's about sending an object, because i have to cast it...

##### Share on other sites
basically, when i'm trying to send an object, i've got the following excepttion

java.io.NotSerializableException: org.unisoft.client.Table
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at org.unisoft.client.Client.mouseClicked(Client.java:260)
at java.awt.Component.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Button.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)

the type of the object i would like to send is Table. The client and the server have got a copy of that class.

##### Share on other sites
Quote:
 Original post by jolyqrbasically, when i'm trying to send an object, i've got the following excepttionjava.io.NotSerializableException: org.unisoft.client.Table the type of the object i would like to send is Table. The client and the server have got a copy of that class.

If you look at the most important line of that exception information (the first one ), it says "java.io.NotSerializableException: org.unisoft.client.Table"

This means the class "Table" is "NotSerializable", so you cannot send it via the methods I described. I don't use java often enough to give a detailed work-around, but you need to copy all the important data from the Table object into a class you define and send that.

Another problem here is that Table sounds like quite a large, complex object. Perhaps you could allow the client to send a command specifying exactly the data it wants from the table, and send only that data instead of the entire object.

##### Share on other sites
Quote:
Original post by rip-off
Quote:
 Original post by jolyqrbasically, when i'm trying to send an object, i've got the following excepttionjava.io.NotSerializableException: org.unisoft.client.Table the type of the object i would like to send is Table. The client and the server have got a copy of that class.

If you look at the most important line of that exception information (the first one ), it says "java.io.NotSerializableException: org.unisoft.client.Table"

This means the class "Table" is "NotSerializable", so you cannot send it via the methods I described. I don't use java often enough to give a detailed work-around, but you need to copy all the important data from the Table object into a class you define and send that.

Another problem here is that Table sounds like quite a large, complex object. Perhaps you could allow the client to send a command specifying exactly the data it wants from the table, and send only that data instead of the entire object.

Basically, I'm trying to make a networking game. So, I would like to use the sockets for sending the client states. I thought I could send an object containing all game states...

##### Share on other sites
Not only the class you wish to send must implement Serializable.. but its attributes, if not primitive types or other Serializable classes, must implement it as well.

But I strongly advice you to break down your data to simple objects... send "instructions" to the clients, not "data"... Avoid sending complex objects, unless really necessary. Think it over dude, I guess you can do it better ;)

Son Of Cain

##### Share on other sites
Ok, I see that networking application are quite complicate of implementing...
I think I'm going to stick with strings and try to create a protocol with it...
Thanks anyway everybody.