简体   繁体   English

Java客户端-服务器聊天协议设计

[英]Java client-server chat protocol design

I need to create a protocol for client-server chat on Java. 我需要为Java上的客户端-服务器聊天创建协议。 I use xml to encode messages between them, but I can't decide how to return decoded data to server. 我使用xml对它们之间的消息进行编码,但是我无法决定如何将解码后的数据返回到服务器。

First time, i created many object implements IAction (eg Auth object represents a packet, about new user in chat) which vary depending on their content. 第一次,我创建了许多对象implements IAction (例如Auth对象代表一个数据包,关于聊天中的新用户),具体取决于其内容。 So, when server receives a socket, it calls my public IAction decode(String s) and then, server should determine what object it is: 因此,当服务器接收到套接字时,它将调用我的public IAction decode(String s) ,然后服务器应确定它是什么对象:

if (myIAction instanceof Auth) {
   server.doMagicAuth((Auth) myIAction);
}

but it was looking ugly to me coz of typecasting and many ifes 但是对我来说,打字和很多ifes看起来很丑

Another approach was to create one common object, called Packet , that can contain intValue , floatValue , stringValue etc. And also it had a flag, that talked about what kind of packet it is. 另一种方法是创建一个称为Packet公共对象,该对象可以包含intValuefloatValuestringValue等。它还带有一个标志,用于说明它是哪种数据包。 But it was the worst idea coz of collisions. 但这是最糟糕的碰撞想法。 For example, how to send 2 int values it this packet? 例如,如何向此数据包发送2个int值? eg password and users_id? 例如密码和users_id?

And the latest idea was to observe server. 而最新的想法是观察服务器。 Server should have many overloaded public void action(IAction a) methods ( action(Auth a) ... etc), and protocol should notify a server depending on what kind of packet it is. 服务器应该有许多重载的public void action(IAction a)方法( action(Auth a) ...等),并且协议应该根据它是哪种数据包来通知服务器。

And i cant decide, what method to use. 而且我无法决定使用哪种方法。 Maybe you have some completely different ideas? 也许您有一些完全不同的想法?

A chat client-server application usually does not send/receive 2 ints or 3 floats or anything like that but just strings. 聊天客户端-服务器应用程序通常不发送/接收2个整数或3个浮点数或类似的东西,而只是发送/接收字符串。 These days I would probably either send JSON objects serialized as strings or just plain strings. 这些天,我可能会发送序列化为字符串或只是纯字符串的JSON对象。

If using XML is a firm requirement you need to define some XML format 如果使用XML是一项严格的要求,则需要定义一些XML格式
(possibly through some XSD even though that's not mandatory in your case) (即使在您的情况下这不是必需的,也可能通过某些XSD)
and stick to that format. 并坚持使用这种格式。 Example: 例:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<message text="Hello"/>

When this is sent from any client, you take it on the server side, 当从任何客户端发送此消息时,您将其放在服务器端,
get the text value and send it from the server to all connected clients. 获取text值,并将其从服务器发送到所有连接的客户端。
That is all they want from you, I believe. 我相信,这就是他们想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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