Sign in to follow this  

[java] Java and Sockets

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
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
in.read((Char [])obj,NULL,sizeof(obj));

Share this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites
Quote:
Original post by jolyqr
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...


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 this post


Link to post
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 this post


Link to post
Share on other sites
Quote:
Original post by Son of Cain
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


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

Share this post


Link to post
Share on other sites
Quote:
Original post by rip-off
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
*** 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 this post


Link to post
Share on other sites
Quote:
Original post by jolyqr

Could 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 threads
ois.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 this post


Link to post
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)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(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 this post


Link to post
Share on other sites
Quote:
Original post by jolyqr
basically, when i'm trying to send an object, i've got the following excepttion

java.io.NotSerializableException: org.unisoft.client.Table
<snip>

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 this post


Link to post
Share on other sites
Quote:
Original post by rip-off
Quote:
Original post by jolyqr
basically, when i'm trying to send an object, i've got the following excepttion

java.io.NotSerializableException: org.unisoft.client.Table
<snip>

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 this post


Link to post
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 this post


Link to post
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.

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this