Serversocket and Socket

Asked

Viewed 160 times

2

I’m trying to create a ServerSocket:


public class RunServer {

public static void main(String[] args) {
    try {

        byte[] buffer = new byte[1024];
        String passwordCript;

        ServerSocket socketRecepcao = new ServerSocket(22300);
        System.out.println("Servidor esperando conexão na porta 22300");

        while (true) {

            Socket socketConexao = socketRecepcao.accept();
            System.out.println("Conexão estabelecida na porta "
                    + socketConexao.getPort());

            InputStream is = socketConexao.getInputStream();
            OutputStream os = socketConexao.getOutputStream();

            is.read(buffer);

            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(buffer, 0, buffer.length);

            BigInteger hash = new BigInteger(1, md.digest());
            passwordCript = hash.toString(16);

            buffer = passwordCript.getBytes();
            os.write(buffer);

            socketConexao.close();
        }

    } catch (NoSuchAlgorithmException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }
}

NOTE: It’s a simple code to create ServerSocket,


But I get this exception:

java.net.BindException: Address already in use: JVM_Bind
    at java.net.DualStackPlainSocketImpl.bind0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketBind(Unknown Source)
    at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
    at java.net.PlainSocketImpl.bind(Unknown Source)
    at java.net.ServerSocket.bind(Unknown Source)
    at java.net.ServerSocket.<init>(Unknown Source)
    at java.net.ServerSocket.<init>(Unknown Source)
    at com.iamExport.RunServer.main(RunServer.java:20)

  1. Why is this exception being cast?
  2. What care should I take after the ServerSocket work?

NOTE: I know there are other types of connection like API HttpClient, etc., but I am studying socket...

  • Using Eclipse? Check the Console for multiple instances of the running program.

  • @utluiz, I checked, it’s actually right. I ended up running the Serversocket it went into background... Thank you guys. I am wrong to believe that I need a method to verify that a particular port can be used?

  • Eduardo, put a pad try/catch to handle the exceptions to return the call to the method accept() and in the event of falling into a catch with BindException, shows a more specific message like "port in use".

  • @utluiz, I’ll do it.

1 answer

5


Basically, there is already something listening on this door (22300). Possibly your own program, running in the background -- take a look at the java processes, make sure to kill them all, and try again.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.