參考 - p481、p484
與我對接的業務層使用的是JAVA語言,因此花點時間入門java.下面幾篇博客可能都是關于java的,我覺得在工作中可能會遇到的
簡單的通信
- DailyAdviceClient(客戶端程序)
import java.io.*;
import java.net.*;public class DailyAdviceClient{public void go(){try{Socket s = new Socket("127.0.0.1", 4242);InputStreamReader streamReader = new InputStreamReader(s.getInputStream());BufferedReader reader = new BufferedReader(streamReader);String advice = reader.readLine();System.out.println("Today you should: " + advice);reader.close();} catch(IOException ex) {ex.printStackTrace();}}public static void main(String[] args) {DailyAdviceClient client = new DailyAdviceClient();client.go();}
}
- DailyAdviceServer(服務器端的程序)
import java.io.*;
import java.net.*;public class DailyAdviceServer {String[] adviceList = {"Take smaller bites", "Go for the tight jeans. No they do NOT make you look fat.", "One word: inappropriate", "Just for today, be honest. Tell your boss what you *really* think", "You might want to rethink thath haircut."};public void go(){try {ServerSocket serverSock = new ServerSocket(4242);while(true) {Socket sock = serverSock.accept();PrintWriter writer = new PrintWriter(sock.getOutputStream());String advice = getAdvice();writer.println(advice);writer.close();System.out.println(advice);}} catch (IOException ex) {ex.printStackTrace();}}private String getAdvice() {int random = (int) (Math.random() * adviceList.length);return adviceList[random];}public static void main(String[] args) {DailyAdviceServer server = new DailyAdviceServer();server.go();}
}
- 先運行服務器端代碼,后運行客戶端代碼