首先我们先进行服务端代码的编写工作:
public class BioServerTest {
public static void main(String [] args){
try {
ServerSocket serverSocket = new ServerSocket(8888);
while (true){
Socket socket = serverSocket.accept();
System.out.println("接受到来自外星的信号>>>");
new Thread(new BioServerHandle(socket)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
上面我们开始监听8888端口,启动这个main后,肯定阻塞到accept,等待客户端发送过来消息
public class BioServerHandle implements Runnable{
private Socket socket;
public BioServerHandle(Socket socket){
this.socket = socket;
}
@Override
public void run() {
BufferedReader br = null;
PrintWriter pw = null;
try {
br = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
pw = new PrintWriter(new OutputStreamWriter(this.socket.getOutputStream()),true);
while (true){
String body = br.readLine();
if (body == null){
break;
}
System.out.print("the order is "+body);
String currentTime = "queryTime".equals(body)? new java.util.Date(System.currentTimeMillis()).toString():"No Query";
pw.println(currentTime);
}
} catch (IOException e) {
try {
br.close();
pw.close();
socket.close();
}catch (Exception e1){
}
}
}
}
我们有了服务端提供的ip跟端口,就可以进行通信了,下面直接贴代码
public class BioClient {
public static void main(String [] args){
BufferedReader br = null;
PrintWriter pw = null;
try {
Socket socket = new Socket("127.0.0.1",8888);
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
pw.println("queryTime");
System.out.println("发送了一个查询时间的命令过去");
String result = br.readLine();
System.out.print(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
先启动服务端,进行轮询,阻塞到accept,然后等待客户端的请求
接受到来自外星的信号>>>
the order is queryTime
发送了一个查询时间的命令过去
Sat Apr 28 10:31:21 CST 2018