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)
- Why is this exception being cast?
- 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
@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?
– noNihongo
Eduardo, put a pad
try/catch
to handle the exceptions to return the call to the methodaccept()
and in the event of falling into acatch
withBindException
, shows a more specific message like "port in use".– utluiz
@utluiz, I’ll do it.
– noNihongo