您的位置:首页 > 编程语言 > Java开发

Java socket编程 猜数游戏--2--客户端

2009-12-06 20:09 951 查看
public class ClientApp {

private Socket socket;

private BufferedReader netIn;

private PrintWriter netOut;

private BufferedReader keyboardIn;

static Boolean finished = false;

public ClientApp() throws IOException {

System.out.println("请输入服务器地址,连接本地服务器请输入localhost");

keyboardIn = new BufferedReader(new InputStreamReader(System.in));

try {

if (keyboardIn.readLine().equalsIgnoreCase("localhost")) {

socket = new Socket(InetAddress.getLocalHost(), ServerApp.PORT);

} else {

socket = new Socket(InetAddress

.getByName(keyboardIn.readLine()), ServerApp.PORT);

}

netIn = new BufferedReader(new InputStreamReader(socket

.getInputStream()));

netOut = new PrintWriter(socket.getOutputStream());

} catch (UnknownHostException e) {

System.err.println("连接不到服务器");

System.exit(-1);

}

System.out.println("连接成功");

while (!finished) {

System.out.println("请输入0-100之间的数字");

netOut.println(keyboardIn.readLine());

netOut.flush();

String str = netIn.readLine();

if (str == null) {

finished = true;

break;

}

System.out.println(str);

if (str.startsWith("OK")) {

finished = true;

break;

}

}

netIn.close();

netOut.close();

keyboardIn.close();

socket.close();

}

public static void main(String[] args) throws IOException {

new ClientApp();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: