简体   繁体   中英

What is a good way to implement Sockets?

dear stackoverflow community. Currently, I am working on a project. This project shall have a server and clients connecting to it. Because of their simplicity, I'd like to use Java's integrated ServerSockets and Sockets.

In my project, data shall be sent from the client to the server and opposite.

My initial idea is to just send JSON and then parse it as receiver and get the data from that. I'm a little unsure about that though, since JSON isn't something that's integrated into Java, but comes from Java script. Also, I'm currently using a Multithreaded-Socket-Server, so I have a ClientHandler Thread class. In that class, the messages were received, parsed and the "action" parameter was read out of the JSON and then I did a switch statement with multiple actions and their functions. I don't think that's a good way of doing that either.

So, my question is: How can I do that better, and maybe do I have to use something else?

Thanks in advance.

It is true that JSON grew out of JavaScript, but it is a reasonable definition language on its own and I don't see any reason you shouldn't use it. There are libraries for parsing it so you don't have to.

Assuming your JSON structures are different for different purposes, and complex enough to need different classes to represent them, I like the idea of the JSON having a parameter that identifies the class to which it belongs, after which you can hand off parsing to a class that understands the designated output. Then a class can read the JSON, get the type, and some the specific parsing routine can go from there to an object created for the purpose.

I don't see anything wrong with an action string, either; it's served well enough for Swing and some other UIs, after all. Instead of branching out to a function, depending on complexity again, you could have action classes that all implemented an interface, and the action 'verb' could tell you which one (out of a map, say?) to get and execute the 'performAction()' method on or whatever you want to call it.

I don't know how clear this is from a quick description; would be willing to chat about it in an SO chat room if you care about it.

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