问题遇到的现象和发生背景
package Serversocket;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Serversocket_Android {
private static final int PORT = 9999; //设置端口号
private List<Socket> mList = new ArrayList<Socket>(); //用ArrayList实现多个用户
private ServerSocket server = null;//服务器
private ExecutorService mExecutorService = null;
private String receiveMsg;//接受的信息
private String sendMsg;//发送的信息
public static void main(String[] args) {
new Serversocket_Android();
}
public Serversocket_Android() {
try {
server = new ServerSocket(PORT);
mExecutorService = Executors.newCachedThreadPool();
System.out.println("服务器已启动...");
Socket client = null;
while (true) {
client = server.accept();
mList.add(client);//客户端加入ArrayList
mExecutorService.execute(new Service(client));
}
} catch (Exception e) {
e.printStackTrace();
}
}
class Service implements Runnable {
private Socket socket;
private BufferedReader in = null;
private PrintWriter printWriter=null;
public Service(Socket socket) {
this.socket = socket;
try {
printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter( socket.getOutputStream(), "UTF-8")), true);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream(),"UTF-8"));
printWriter.println("成功连接服务器"+"(服务器发送)");
System.out.println("成功连接服务器");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
while (true) {
if ((receiveMsg = in.readLine())!=null) {
System.out.println("receiveMsg:"+receiveMsg);
if (receiveMsg.equals("0")) {
System.out.println("客户端请求断开连接");
printWriter.println("服务端断开连接"+"(服务器发送)");
mList.remove(socket);
in.close();
socket.close();
break;
} else {
sendMsg = "我已接收:" + receiveMsg + "(服务器发送)";
printWriter.println(sendMsg);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
问题相关代码,请勿粘贴截图
运行结果及报错内容
java.net.BindException: Address already in use: bind
at java.base/sun.nio.ch.Net.bind0(Native Method)
at java.base/sun.nio.ch.Net.bind(Net.java:550)
at java.base/sun.nio.ch.Net.bind(Net.java:539)
at java.base/sun.nio.ch.NioSocketImpl.bind(NioSocketImpl.java:643)
at java.base/java.net.ServerSocket.bind(ServerSocket.java:396)
at java.base/java.net.ServerSocket.<init>(ServerSocket.java:282)
at java.base/java.net.ServerSocket.<init>(ServerSocket.java:173)
at Serversocket.Serversocket_Android.<init>(Serversocket_Android.java:31)
at Serversocket.Serversocket_Android.main(Serversocket_Android.java:26)
我的解答思路和尝试过的方法
我想要达到的结果