我在Android上遇到TCP服务器问题。服务器必须管理来自同一用户的多个传入连接。我收到了以下错误:
02-06 17:37:44.800: W/System.err(9859): java.net.BindException: bind failed: EADDRINUSE (Address already in use)
02-06 17:37:44.800: W/System.err(9859): at libcore.io.IoBridge.bind(IoBridge.java:89)
02-06 17:37:44.800: W/System.err(9859): at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:150)
02-06 17:37:44.800: W/System.err(9859): at java.net.ServerSocket.bind(ServerSocket.java:318)
02-06 17:37:44.800: W/System.err(9859): at java.net.ServerSocket.bind(ServerSocket.java:281)
02-06 17:37:44.800: W/System.err(9859): at sample.services.TCPService$1.run(TCPService.java:84)
02-06 17:37:44.804: W/System.err(9859): Caused by: libcore.io.ErrnoException: bind failed: EADDRINUSE (Address already in use)
02-06 17:37:44.804: W/System.err(9859): at libcore.io.Posix.bind(Native Method)
02-06 17:37:44.804: W/System.err(9859): at libcore.io.ForwardingOs.bind(ForwardingOs.java:39)
02-06 17:37:44.804: W/System.err(9859): at libcore.io.IoBridge.bind(IoBridge.java:87)
02-06 17:37:44.804: W/System.err(9859): ... 4 more
我添加setReuseAddress(true)
但没有任何改变。我正在使用的代码如下。哪里出错了?感谢
public void onStart(Intent intent, int startid) {
t = new Thread(){
public void run() {
try {
Log.d("TCP", "Server: Creating server.");
ServerSocket ss = new ServerSocket();
ss.setReuseAddress(true);
ss.bind(new InetSocketAddress(TCPPORT));
while(true) {
//Server is waiting for client here, if needed
Log.d("TCP", "Server: Waiting on packet!");
Socket s = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String msg = input.readLine();
......
}
}
};
t.start();
}
答案 0 :(得分:3)
我解决了!问题是套接字必须在setReuseAddress()语句之后绑定。