import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
// liuhailong2008#ruc.edu.cn 微博: @刘海龙RUC
public class HelloClient {
public static final String SERVER_IP
= "127.0.0.1";
public static final int SERVER_PORT =
9527;
public static void main(){
String command = "What's the time?";
String serverRet = callServerMethod(command);
System.out.println("客户端发送命令:"+command);
System.out.println("服务器端返回:"+serverRet);
}
public static
String callServerMethod(String command) {
String ret = "";
try {
Socket socket = new Socket(SERVER_IP,
SERVER_PORT);
// 发送命令
OutputStream socketOut = socket.getOutputStream();
command += "\r\n";
socketOut.write(command.getBytes("UTF-8"));
// 接收服务器的反馈
BufferedReader br = new
BufferedReader(new InputStreamReader(
socket.getInputStream(), "UTF-8"));
ret = br.readLine();
System.out.println("Server return : "
+ ret);
// 发送关闭命令
socketOut.write("sb\r\n".getBytes("UTF-8"));//
服务器端接收到“sb”会终止本次连接
} catch (IOException e) {
//e.printStackTrace();
System.err.println("同服务器交互时"+e.getMessage());
}
return ret;
}
}
// liuhailong2008#ruc.edu.cn 微博:
@刘海龙RUC