简体   繁体   中英

Convert Socket to String and vice versa

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?

For example, consider a Socket ss . What I want is some thing like this:

String strss = ss.tostring();

and later

Socket s = new Socket(strss);

I want to save the Socket (ie 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:

To string:

Socket s = ...;
String hostAndPort = s.getInetAddress().getHostAddress();
hostAndPort = hostAndPort + ":" + s.getPort();

then back:

String host = hostAndPort.substring(0, hostAndPort.indexOf(':'));
int port = Integer.parseInt(hostAndPort.substring(hostAndPort.indexOf(':') + 1));
Socket s = new Socket(host, port);

I want to save Socket into database (as string )

That is not possible.

You are welcome to save the host and port you used to open a socket to a database.

You can't turn a socket into a string, except as a simple summary. Instead, you should send data over the socket.

try{
Socket ss=new Socket();
BufferedReader in=new BufferedReader(new InputStreamReader(ss.getInputStream()));
PrintWriter out=PrintWriter(ss.getOutputStream()));
String line=in.readLine(); //reads a line, repeat as necessary
out.println("foo"); //Writes a line
} catch (IOException e){
     e.printStackTrace();
}

Output buffering is left as an exercise to the reader.

You can't save a socket into a database. It doesn't make any sense.

To recreate a socket later, you just need the host address and port number .

  • If each existing socket has a different host address and port number then you will need to store both in your database:

    • If you have no choice about storing all the data in a single string, then you will need to encode both host address and port number in that string, in the way suggested by Mattias or something similar.

    • It would be better though, to store the host address and the port number in the database separately, that way you do not have the added complication of creating and parsing the strings later.

  • If your socket is always opened to the same port however, you could just save the host address in the database.

For example, to get the host address :

String strss = ss.getInetAddress().getHostAddress();

then to recreate the socket:

Socket s = new Socket(strss, KNOWN_PORT);

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