在下面的示例中,在while
循环中
http://www.avajava.com/tutorials/lessons/how-do-i-make-a-socket-connection-to-a-server.html
在客户端类中,他不断重新创建套接字对象。这种方法是否正确?我不能重用1个套接字吗?
package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class TestClientSocket {
public static void main(String args[]) throws IOException {
final String host = "localhost";
final int portNumber = 81;
System.out.println("Creating socket to '" + host + "' on port " + portNumber);
while (true) {
Socket socket = new Socket(host, portNumber); //THIS HERE ISN'T GOING TO BE SLOW ??
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
System.out.println("server says:" + br.readLine());
BufferedReader userInputBR = new BufferedReader(new InputStreamReader(System.in));
String userInput = userInputBR.readLine();
out.println(userInput);
System.out.println("server says:" + br.readLine());
if ("exit".equalsIgnoreCase(userInput)) {
socket.close();
break;
}
}
}
}