Server:
ServerSocket server = new ServerSocket(PORT, 1); // 打开Server并监听
Socket client = server.accept(); // block 直到有client,得到对应socket 句柄
System.out.println("Client connected");
while (true) {
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream())); // 得到输入流
System.out.println("Read from client");
String textLine = reader.readLine() + "/n";
if (textLine.equalsIgnoreCase("EXIT/n")) {
System.out.println("EXIT invoked, closing client");
break;
}
if (textLine.equalsIgnoreCase("STOP/n")) {
System.out.println("Stop server");
running = true;
break;
}
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream())); // 对应
输出流
System.out.println("Echo input to client");
writer.write("ECHO from server: " + textLine, 0, textLine.length() + 18);
writer.flush();
}
client.close(); // 关闭
Client:
socket = new Socket(ip, Integer.parseInt(port)); // 得到server socket 句柄
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); // 写数据流
reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 读数据流
// send input terminated with /n
String input = socketData;
writer.write(input + "/n", 0, input.length() + 1);
writer.flush();
// read back output
output = reader.readLine();
Log.d(Constants.LOGTAG, " " + SimpleSocket.CLASSTAG + " output - " + output);
// send EXIT and close
writer.write("EXIT/n", 0, 5);
writer.flush();