一个非常简单的服务器程序:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class AdviceServer {
String[] adviceList = {"Take smaller bites", "Go for the tight jeans. No they do NOT make you look fat",
"One word: inappropriate", "Just for today, be honest. Tell your boss what you *really* think",
"You might want to rethink that haircut"};
public void go() {
try {
ServerSocket serverSocket = new ServerSocket(4200);
while(true) {
Socket socket = serverSocket.accept();
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
String advice = getAdvice();
printWriter.println(advice);
printWriter.close();
System.out.println(advice);
}
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
private String getAdvice() {
int random = (int) (Math.random() * adviceList.length);
return adviceList[random];
}
public static void main(String[] args) {
AdviceServer adviceServer = new AdviceServer();
adviceServer.go();
}
}
run 了一次之后,再 run 就报“java.net.BindException: Address already in use”的异常。
也就是说,第一次 run 的时候,new ServerSocket(4200) 就告知服务器,4200 这个端口被我的应用绑定了,再次 new 的时候肯定会报异常啦,我自己写的程序没有报异常,是因为忘了这句
e.printStackTrace();
只是没打印出来而已。。