我尝试使用SSLServerSocket创建一个Android服务器。我做了一个密钥库并开始制作服务器。我按如下方式初始化服务器:
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
InputStream inputStream = context.getResources().openRawResource(R.raw.server);
keyStore.load(inputStream, "passwd".toCharArray());
String keyalg = KeyManagerFactory.getDefaultAlgorithm();
kmf.init(keyStore, "passwd".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyalg);
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), null, null);
SSLServerSocket ss = (SSLServerSocket) context.getServerSocketFactory().createServerSocket();
inputStream.close();
//Here comes the error
ss.accept();
因此,如果我尝试接受客户端(没有客户端尝试连接),我会收到错误。
java.net.SocketException: accept failed: EINVAL (Invalid argument)
at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:110)
at java.net.ServerSocket.implAccept(ServerSocket.java:203)
at com.android.org.conscrypt.OpenSSLServerSocketImpl.accept(OpenSSLServerSocketImpl.java:184)
at de.turtc.util.ServerUtil.run(ServerUtil.java:88)
Caused by: libcore.io.ErrnoException: accept failed: EINVAL (Invalid argument)
at libcore.io.Posix.accept(Native Method)
at libcore.io.BlockGuardOs.accept(BlockGuardOs.java:55)
at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:98)
没有SSLServerSocket就行了!我没有得到任何有关此错误的信息!
答案 0 :(得分:0)
问题是:我没有给服务器端口。
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
InputStream inputStream = context.getResources().openRawResource(R.raw.server);
keyStore.load(inputStream, "passwd".toCharArray());
String keyalg = KeyManagerFactory.getDefaultAlgorithm();
kmf.init(keyStore, "passwd".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyalg);
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), null, null);
SSLServerSocket ss = (SSLServerSocket) context.getServerSocketFactory().createServerSocket(4444);
inputStream.close();
ss.accept();
所以我改变了:
SSLServerSocket ss = (SSLServerSocket) context.getServerSocketFactory().createServerSocket();
到
SSLServerSocket ss = (SSLServerSocket)context.getServerSocketFactory().createServerSocket(4444);
这解决了我的问题!