插座转换为字符串,反之亦然 [英] Convert Socket to String and vice versa
问题描述
我socket编程为Android(在Java中)。如何将我的插座转换成字符串并转换该字符串重新presentation回插座?
I'm socket programming for Android (in Java). How can I convert my socket to a string and convert that string representation back to a socket?
例如,假设有一个插座SS
。我要的是一些像这样的事情:
For example, consider a Socket ss
. What I want is some thing like this:
String strss = ss.tostring();
和后来
Socket s = new Socket(strss);
我要保存的插座(即重建后的插座所需的详细信息)到数据库中(作为一个字符串)之后,我需要重新转换它插座我的应用程序使用它!
I want to save the Socket (i.e. the details needed to recreate that socket later) into a database (as a string) and after that I need to reconvert it to Socket to use it in my app!
推荐答案
奇怪的问题,但您可以提取您需要重新创建一个字符串插座的信息。
如果没有错误检查等:
Strange question but you can extract the info you need to recreate the socket from a string. Without error checking etc:
要字符串:
Socket s = ...;
String hostAndPort = s.getInetAddress().getHostAddress();
hostAndPort = hostAndPort + ":" + s.getPort();
然后回:
String host = hostAndPort.substring(0, hostAndPort.indexOf(':'));
int port = Integer.parseInt(hostAndPort.substring(hostAndPort.indexOf(':') + 1));
Socket s = new Socket(host, port);
这篇关于插座转换为字符串,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!