-1

I have a very basic understanding of clients, servers, sockets, input and output streams, etc. related to having servers. However, my socket that I created does not seem to work. I used many unused ip and ports, and even tried my own computer's ip. The Socket I created does not throw an IOException, or break anything. Anything past the creation of my socket object never happens.

public class ClientHello {
   public static void main(String [] args) {
      String ip = "91.202.240.208";
      int port = 51678;

    try {
        System.out.println("1");

        Socket sock = new Socket(ip, port);

       System.out.println("2");

        DataOutputStream stream1 = (DataOutputStream) sock.getOutputStream();
         stream1.writeUTF("Hi server!");

         DataInputStream stream2 = (DataInputStream) sock.getInputStream();
         System.out.println(stream2.readUTF());

        sock.close();

    }catch(IOException e) {
        e.printStackTrace();
    }

   }
}

Additionally, the ip and port is from a random Ukrainian thingy.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 2
    `Socket sock = new Socket(ip, port);` creates a `Socket` and tells it to *connect* to that `ip` and `port`. Why do you think somebody awaits a connection from you there? – Fureeish Dec 30 '19 at 00:51
  • 2
    @Fureeish - It should eventually time out and give the OP an exception. Perhaps the OP is not waiting long enough .... – Stephen C Dec 30 '19 at 01:09
  • 1
    A socket InputStream is **not** a `DataInputStream`, so your cast would result in a `ClassCastException` at runtime, not do nothing. A `DataInputStream` (and its counterpart `DataOutputStream` is a very specific data-primitive serialization protocol that is not generally applicable, unless both sides of the connection agreed to use that, and if that is the case you need to wrap the socket input/output stream, not cast it. – Mark Rotteveel Dec 31 '19 at 07:39
  • 1
    Your question doesn't make any sense whatsoever. When I try to connect to your random Ukrainian host, rather than blocking indefinitely as you claim, it times out after ~20 seconds. It doesn't make any sense to expect a 'random Ukrainian host' to be even running, let alone to speak `read/writeUTF()`. Try again with your *own* server and your own application protocol. – user207421 Dec 31 '19 at 07:44

1 Answers1

2

For the IP and port in Socket, you need to put the server socket's IP address and port so it can connect to server. Not just some random IP address.

You need to make a ServerSocket for your server first, and then with the Server's IP and port (you can specify the port when you make sever socket, and ip will be your IP) and then you that code to connect to server.

user207421
  • 305,947
  • 44
  • 307
  • 483
chuu
  • 128
  • 6