实现反转,但是运行也能反转,就会返回异常java.net.BindException: Address already in use: JVM_Bind
是怎么回事啊
public class Test10_Server {
public static void main(String[] args) {
Socket socket = null;
try {
while(true){
//创建绑定端口8888的对象ServerSocket
ServerSocket serverSocket = new ServerSocket(8888);
//接收客户端请求,得到Socket
socket = serverSocket.accept();
//创建带缓冲的字符读入流
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//读取字符串
String sr = br.readLine();
PrintStream ps = new PrintStream(socket.getOutputStream());
//将反转后的字符串打印到客户端屏幕上
ps.println(new StringBuffer(sr).reverse());
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(socket != null){
try {
socket.close();
//抓获异常打印堆栈信息
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public class Test10_Client {
public static void main(String[] args) {
Socket socket = null;
try {
//创建Socket, 请求服务端
socket = new Socket(InetAddress.getLocalHost(), 8888);
while(true){
//创建带缓冲的字符读入流
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
//创建Scanner输入流
Scanner scanner = new Scanner(System.in);
//提示输入
System.out.println("请输入一个字符串:");
//从键盘输入字符串
String line = scanner.nextLine();
//发送到服务器
ps.println(line);
//读取服务器发回的字符串并打印
System.out.println(br.readLine());
}
//捕获异常,打印堆栈信息
} catch (Exception e) {
e.printStackTrace();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
|
|