简体   繁体   中英

Java - Sending objects with sockets and using a address besides localhost

So I am starting to learn sockets and I found two problems
1.

   InetAddress address = InetAddress.getByName("75.73.111.104");
    @SuppressWarnings("resource")
    Socket socket = new Socket(address, 57823);
    ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out.writeObject("string");

So I have that code but whenever I try to connect with it it says" Connection refused: connect " But that code was working fine with localhost and it is port forwarded so whats wrong with that.
2.

@SuppressWarnings("resource")
ServerSocket serverSocket = new ServerSocket(57823);
Socket clientSocket = serverSocket.accept();
ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());                                   
BufferedInputStream in = new BufferedInputStream(clientSocket.getInputStream());
if(in.toString() != null)
{
    System.out.println(in.toString());
}

When I use that code it does not print the "string" that I typed earlier it gives me the classname@random numbers. And it does not see the result as a string but as a object so how do I save objects I have sent?

Flush the outputstream

out.writeObject("string");
out.flush();

And at server side read the data from stream

 String data = in.readLine();// read data from stream sent by client
System.out.println(data);

If you are writing with ObjectOutputStream then read with ObjectInputStream .

ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());

String data = in.readUTF();// reading String Object

Your trouble is not with java but with networking. You can't usually access your external IP from the inner network.

Try using an external proxy server or ask someone else outside your network to host the client or the server.

Here you can see how to configure a proxy in java. You should use a socks proxy.

Here you have a list of public socks proxies.

Since you're using an ObjectOutputStream to serialize the object, You'll need to use a complementary ObjectInputStream to deserialize the object on the other side.

I think the ObjectInputStream.readObject() method should do the trick.

Haven't tested it myself, but give this a try and see what happens:

@SuppressWarnings("resource")
ServerSocket serverSocket = new ServerSocket(57823);
Socket clientSocket = serverSocket.accept();
ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
System.out.println(in.readObject());

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