简体   繁体   English

简单的Java TCP套接字协议

[英]Simple Java TCP socket protocols

I'm trying to find a reliable way to send control messages that obey a defined protocol in order to tell the server what kind of data he will receive. 我试图找到一种可靠的方式来发送服从已定义协议的控制消息,以告诉服务器他将接收哪种数据。 For example, I want to send a pure text message to invoke a remote method: 例如,我要发送纯文本消息来调用远程方法:

#METHOD1#CLOSE#

or I want to send a serialized object to the server: 或者我想将序列化的对象发送到服务器:

#OBJECT# .......here comes the serialized object data....#CLOSE#

So basically I just want to send string control messages that are completely independent of the stream content that follows. 因此,基本上我只想发送完全独立于后续流内容的字符串控制消息。

By wrapping an input stream into a Scanner object I'm able to extract strings from the input stream, but if this stream is a serialized object then the object can't be restored afterwards. 通过将输入流包装到Scanner对象中,我可以从输入流中提取字符串,但是如果该流是序列化的对象,则此后将无法还原该对象。 Thanks for any help. 谢谢你的帮助。

You can use a scheme like Base64 (eg use a library from Apache) to encode the Object from bytes into a string and then back. 您可以使用诸如Base64之类的方案(例如,使用来自Apache的库)来将Object从字节编码为字符串,然后返回。

ByteArrayOutputStream baos = new ByteArrayOutputStream();
new ObjectOutputStream(baos).writeObject(object);
String serializedObject = Base64.encode(baos.toByteArray());

byte[] bytes = Base64.decode(serializedObject);
ByteArrayInputStream baos = new ByteArrayInputStream(bytes);
Object object = new ObjectInputStream(baos).readObject()

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

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