socket程式設計程式碼示例(單執行緒)
阿新 • • 發佈:2019-02-08
客戶端程式碼如下:
伺服器端程式碼如下:import java.io.*; import java.net.*; public class DailyAdviceClient { public void go(){ try { Socket s=new Socket("127.0.0.1",4242);//建立對伺服器的Socket連線 //客戶端從伺服器讀取資料 //建立連線到socket上低層輸入串流的InputStreamReader //InputStreamReader是低層和高層串流間的橋樑 //s.getInputStream()從Socket取得輸入串流 InputStreamReader streamReader=new InputStreamReader(s.getInputStream()); //建立BufferedReader來讀取 BufferedReader reader=new BufferedReader(streamReader); String adviceString=reader.readLine(); System.out.println("Today you should: "+adviceString); //客戶端向伺服器傳送資料 //建立不帶自動行重新整理的PrintWriter物件, //如果新增第二個引數true,則為自動重新整理,不需要寫writer.flush()這行程式碼 PrintWriter writer=new PrintWriter(s.getOutputStream()); writer.println("Hello,I am Client2!"); writer.flush();//刷新發送資料 System.out.println("此套接字連線的遠端地址:"+s.getInetAddress().getHostAddress()); System.out.println("此套接字繫結的本地地址:"+s.getLocalAddress().getHostAddress()); System.out.println("此套接字繫結的本地埠:"+s.getLocalPort()); System.out.println("此套接字連線到的遠端埠:"+s.getPort()); s.close();//關閉socket } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[]args){ DailyAdviceClient client=new DailyAdviceClient(); client.go(); } }
import java.io.*; import java.net.*; public class DailyAdviceServer { String[] adviceList={"Take smaller bites","One word: inappropriate","" + "Just for today,be honest","Tell your boss"}; public void go(){ try { //伺服器應用程式對特定埠創建出ServerSocket物件 //這會讓伺服器應用程式監聽來自4242埠的客戶端請求 ServerSocket serverSocket=new ServerSocket(4242); //伺服器進入無窮迴圈等待客戶端的請求 while(true){ System.out.println("等待客戶端連線..."); //接收到使用者連線請求後,此方法會返回一個socket,以便於客戶端通訊 //此socket的埠號和serverSocket的埠號不同 Socket sock=serverSocket.accept();//此方法會阻塞直到有連線請求到達 System.out.println("此套接字連線的地址:"+sock.getInetAddress().getHostAddress()); System.out.println("此套接字繫結的本地地址:"+sock.getLocalAddress().getHostAddress()); System.out.println("此套接字繫結的本地埠:"+sock.getLocalAddress()); System.out.println("此套接字連線到的遠端埠:"+sock.getPort()); //伺服器向客戶端傳送資料 PrintWriter writer=new PrintWriter(sock.getOutputStream()); String adviceString=getAdvice(); writer.println(adviceString); writer.flush(); System.out.println(adviceString); //伺服器接收客戶端傳送的資料 InputStreamReader streamReader=new InputStreamReader(sock.getInputStream()); BufferedReader reader=new BufferedReader(streamReader); String adviceStringREC=reader.readLine(); System.out.println("REC: "+adviceStringREC); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String getAdvice(){ int random=(int)(Math.random()*adviceList.length); return adviceList[random]; } public static void main(String []args){ DailyAdviceServer server=new DailyAdviceServer(); server.go(); } }