简体   繁体   中英

How to establish network communication between two Java servers

at the moment I have two Java Servers(Game and Database servers) in the future there will be more. I need establish network communication between its, since they can be run on different machines.

Initially, I thought to serialize objects and send them over the network, let's say you need to save the user to the database, I serialize the object and send it to save, but how can we be with the deletion, modification, etc... So I think this approach is not very preferable.

In this regard, the question may be there are any ready-made tools or technologies for this purpose, or it may be worth to implement the Protocol itself(but then how better to do it)?

Start with a protocol.

Define what can be sent and what data a server would need. You may use serialization if needed, but along with that you should provide additional information on what is being sent and, if needed, what to to with it.

And, of course, there is no ready implementation for your business logic.

You decide what to send, when and how.

Define your own protocol using JSON as follows: Design an object containing the data you wish to pass back and forth, or a separate entity for each direction. There are several ready made solutions to convert an object to a JSON string and back. Then send the string over TCP - see for example Sending a JSON object over TCP with Java .

So there are various mechanism through which two servers (API's) can communicate, starting from RMI, RPC to REST, JMS. You'll have to decide what mechanism you want to implement. REST is one of the good example, whre depending upon what action you want to perform, you choose appropriate Http Method, so while insert/update use POST/PUT and pass the data in body. Whereas while delete(DELETE) just call the api(method), at worst some flag can be used.

JMS is another mechanism which could be handy, where you send the messages and perform the action. Similar to REST you define the message format and message header could be used to define the action you want to perform.

One of the old fashioned ways of doing such a thing, like you said communicate with Database server, would be define a DB User Stored Procedures(USP) or a function & call USP/function by passing appropriate parameters. Off-course you'll have to write client application for perform this passing/calling task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM