I'm a Delphi developer and recently I decided to port one of my programs to java and I'm doing the server side program in java to make it cross-platform.
In Delphi, I could easily send a record as an array of bytes through TCP but I don't have much experience in java and I have no idea how to do it in an easy but moderated way.
Here is a sample of my data record:
type
Tlogin = record
username : string[50];
password : string[50];
version : word;
end;
And I would just simply send this type of record after making it an array of bytes.
Any ideas how to make such data records in java and how do I set size for strings, or any better suggestions to handle strings for sending them through TCP.
In Java, you simply send objects over the sockets between a client and server and there are a number of ways to do that. For a related reference please visit
Sending objects over Java sockets
For a more step by step example visit the following link:
JGuru - Sending objects over a socket
In your case your object would look as follows
class TLogin implements Serializable
{
private String userName;
private String password;
private int version;
//implement your objects methods below
}
Fields within the object that you do not want to participate in serialization and de-serialization can be marked as transient
For a detailed step by step example of serialization visit
Java Serialization Example
Edit based on the comment provided to my earlier response.
Serialization in simple words : It is a technique where-in a Java object is converted to a byte sequence (essentially, all fields of the object except those marked transient are a part of this byte sequence). This byte sequence can then be used to re-construct the object at a later point of time. The byte sequence obtained by serializing an object can be either persisted to a store or transmitted over a network channel, in order to have it re-construct the object at a later stage.
Serialization is at the core of a lot of communication protocols that happen within a client server environment within Java using either of RMI, Sockets or SOAP.
Having talked about serialization , we come to the client-server problem.
In case, the plan is only to port the server side code to Java then you have the following options to enable communication between the client and server:
Design the server to use SOAP/REST to communicate with the Delphi client.
Augment your record with a header data structure that contains information about the length and type of the data being stored and use this header within the client transmitted byte sequence on the server side to re-construct the object.
However, in my opinion the first method is better than the second since
it is a standard inter-operable technique.If at a later point of time you wish to port the client to some other language like C# or Python, you do not need to change the server.
it lets the web service infrastructure handle the nitty gritty of
SOAP/REST serialization and lets you focus on the business logic
I hope this lengthy answer points you in a direction towards the solution
Related
Basically I am doing some networking with a client and server sending "packets" back and forth to each other. I have it working with basic variable data such as ints or strings passing back and forth, however now I want to pass an object.
So I know I have to serialize the data of the object to pass it through the socket. That is working as well (as I can get the correct information if I serialize then de-serialize right away) but the problem comes in when my server receives a packet.
My server interprets packet data based on the first 2 characters of the packet. So 01foobar is a type of packet correlating to whatever "01" is assigned to and 02foobar is a different packet as well. So I don't know the best way to do this with an object attached. What is mean is this...
The way I have tried to do it right now is, serialize my object and get it's string. Then append on 03 to the front. So basically I have a string that looks like 03[B#3e9513b7 (or whatever) then do getBytes() on that string which gives me another byte[] (so I can send it through the socket). Then when the server receives that information, I can append the 03 off and I'm left with just [B#3e9513b7. The problem is, [B#3e9513b7 is now a string, and not a byte[] and in order to deserialize I need to send it the same byte[] as it gave me when it serialized that data. So that got me looking into a way to make [B#3e9513b7 BE the byte[] (aka, so when I do toString() on that new byte[] it returns [B#3e9513b7) but was having issues assigning it like that because it would give me a new byte[] for [B#3e9513b7 as a string. So obviously then, when I send it to be deserialized it has a byte[] that it doesn't know what to do with and throws an error.
So I have to imagine there's a better way to do this, and I'm just making things more complicated than they should be. Any recommendations? I can provide code snippets if needed.
Thanks guys!
Edit: I guess I should mention that I am using Java with using UDP sockets.
If you are looking for a reliable and efficient solution for client-server communication, I would suggest to look at Netty.
Regarding how to serialize/deserialize your objects, you have many choices as Java serialization, XML, JSON ...
You would have to pass your serialized objects in UDP datagrams. However, be aware that UDP datagram size is limited. If you're exchanging big objects, you may want to switch to TCP transport which is more reliable.
You may also want to look at SOAP/REST web services.
I am using TCP Sockets and I am a beginner in Java and Sockets too. The scenario is that the client,depending on server 's answer, may send either int or a string. I need to save the output stream of the client, in a variable on the server 's side, so i can use it in if statements and so on. But how could I do this when i don t know if the stream sent is an integer or a string?
I have made a very simple example, because my code is huge and messy and i don t want to make it more complex
Client Side:
serverSentence=inFromServer.readLine();
if (serverSentence.equals("Hello"))
{
anInt=readUserInput.nextInt();
outToServer.write(anInt);
}
else
{
outToServer.writeBytes("Hello word!"+'\n');
}
So how I could do this, I mean saving in a variable the Client 's output stream, in the Server 's side (or the opossite), so I could use it in loops and ifs?
Use Object. A reference typed as an Object may refer to Integer or String. Another story is of course deserializing the incoming data as either. If the problem has to do with not knowing how to interpret serialized data, include some sort of flag to indicate what the data is.
You should design your protocol of communication between server and client in such a way that server would be able to read some information (you could call it standard header), and based on that would know how to interpret the remaining bytes sent by the client.
And then you'll know how to read the data from client, and where to store it.
I have a chat program implemented in Java. The client can send lots of different types of information to the server (i.e, Joins the server and sends username, password; requests a private chat with another user on the server, disconnects from the server, etc).
I'm looking for the correct way to have the server/client differentiate between 'text' messages that are just meant to be chat text messages sent from one client to the others, and 'command' messages (disconnect, request private chat, request file transfer, etc) that are meant for the server or the client.
I see two options:
Use serialized objects, and determine what they are on the receiving end by doing an 'instanceof'
Send the data as a byte array, reserving the first N bytes of the array to specify the 'type' of the incoming data.
What is the 'correct' way to do this? How to real protocols (oscar, irc) handle this situation?
I've googled around on this topic and only found examples/discussions centering on simple java chat applications. None that go into detail about protocol design (which I ultimately intend to practice).
Thanks to any help...
Second approach is much better, because serialization is a complex mechanism, that can be easily used in a wrong way (for example you may bind yourself to internal content of a concrete serialized class). Plus your protocol will be bound to JVM mechanism.
Using some "protocol header" for message differentiation is a common way in network protocols (FTP, HTTP, etc). It is even better when it is in a text form (people will be able to read it).
You typically have a little message header identifying the type of content in all messages, including standard text/chat messages.
Either of your two suggestions are fine. (In your second approach, you probably want to reserve some bytes for the length of the array as well.)
So I recently followed this tutorial on making a basic chatroom in Java. It uses multithreading and is a "connection-oriented" server. I was wondering how I could use the same Sockets and ServerSockets to send, say, the 3d position of an object instead of just a string?
Currently, the basic chatroom system just sends a string to the server and then the server sends it to all connected clients. What I want is to be able to have a client change the position of an object (most likely their character), and send the change of position to the server. Then (I would imagine) the server would send that change in position to each of the clients connected to it, and each client would in turn render this object at its new position.
I was wondering what the best way to do something like this was?
Would it be to send a string and have the server parse it into a coordinate?
Can I write more than one thing to a DataOutputStream at once?
I feel like I may have explained this poorly, so please ask some clarifying questions.
Thanks!
Create a Domain Object Model for your coordinate system. Then represent the changes to the positions using the objects in the above model. Serialize them into a transportable string like XML, JSON etc. Then unmarshall/deserialize the String to the original object and act upon them.
This separates your transport layer (using sockets to bradcast stuff) from the actual business logic (placement of objects) and the system becomes extendible.
I implemented on Android a small application that sends through a socket connection strings to a server ( C# ).
For now, I only encode the strings I send ( security issues ), but now I need to implement a protocol to have other features on my App like a "keep alive" message, among others.
The procotol was already defined by us, it has a header ( a sequence of bytes ) and the data ( the strings that I sent before ), but because I am not familiar with this I don't know how to start implementing on Java ( client ) the protocol.
Could you point some examples of simple protocols implementation? I need to read bytes, so I can decide what type of action the client is asking from the server, and the other way around too.
My first try would be to create one class for each Message type, and fill the bytes the way i need, in the end each message would be a byte array. But I don't want to start digging on this before I am sure that that's the right path to go.
Thank you for your time.
EDIT
Ended using Protocol Buffers for implementing this:
http://code.google.com/p/protobuf-net/ - for the c# server side
http://code.google.com/p/protobuf-javame/ - for the Android side
I faced the same problem some time ago. If you have enough bandwidth then I suggest you go XML and XML streams, these two technologies fit very well in all platforms and all languages. However, if you are short of bandwidth then yes you can go binary.
Here is the design I usually use:
class AbstractMessage{
byte[] data;
void GenerateHeader(){
// this method generates the message header
}
// Use this method to translate your
// business domain message into a byte array that will go through the network
void abstract byte[] ToByteArray(AbstractMessage);
// Translate received data from network to a business domain message
void abstract AbstractMessage ParseMessage(byte[] receivedData)
}
// And then you can have your messages
class MyMessage extends AbstractMessage{
// In this subclass, you can define how a
// MyMessage object is translated into a byte array
// and vice versa (using ToByteArray and ParseMessage methods)
}
I hope this helps,
Regards,