java代碼實現socket接口通訊(堵塞I/O)
阿新 • • 發佈:2018-08-09
write ice 代碼 args fin true finall tar 輸出
傳統的java實現socket通訊比較簡單實現,不過它屬於堵塞式的I/O流存取,只能由一個線程完成當前任務才能起下個一個線程,無法解決高並發;
1、簡單的socketservice
對每一個Socket連接建立一個Handler處理線程,處理線程對inputstream流中的數據進行相應的處理後,將處理結果通過PrintWriter發送給客戶端,在最後需要關閉輸入流、輸出流和socket套接字句柄資源。
1 public class TimeServer { 2 3 public static void main(String[] args) throws IOException {4 5 int port = 8080;//server 端口采用8080 6 ServerSocket server = null; 7 Socket socket = null; 8 try { 9 server = new ServerSocket(port); 10 while(true){ 11 socket = server.accept(); 12 new Thread(new TimeHandler(socket)).start();13 } 14 } catch (Exception e) { 15 e.printStackTrace(); 16 }finally{ 17 if(server!=null){ 18 server.close(); 19 server =null; 20 System.out.println("the time server close..."); 21 } 22 } 23 }24 25 } 26 27 class TimeHandler implements Runnable{ 28 29 private Socket socket; 30 31 public TimeHandler(){ 32 33 } 34 public TimeHandler(Socket socket){ 35 this(); 36 this.socket = socket; 37 } 38 39 public void run() { 40 System.out.println(Thread.currentThread().getName()+" start success..."); 41 BufferedReader in = null; 42 PrintWriter out = null; 43 try { 44 in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 45 out = new PrintWriter(socket.getOutputStream(),true); 46 while(true){ 47 String str = in.readLine(); 48 if("end".equals(str)){ 49 break; 50 } 51 String time = str+":"+System.currentTimeMillis(); 52 out.println(time); 53 } 54 } catch (Exception e) { 55 e.printStackTrace(); 56 }finally{ 57 if(in!=null){ 58 try { 59 in.close(); 60 } catch (IOException e) { 61 e.printStackTrace(); 62 } 63 in = null; 64 } 65 if(out!=null){ 66 out.close(); 67 out= null; 68 } 69 if(socket!=null){ 70 try { 71 socket.close(); 72 } catch (IOException e) { 73 e.printStackTrace(); 74 } 75 socket =null; 76 } 77 } 78 79 } 80 }
2、socketclient
1 public class TimeClient { 2 3 public static void main(String[] args) { 4 int port = 8080; 5 Socket socket = null; 6 BufferedReader in =null; 7 PrintWriter out =null; 8 9 try { 10 socket = new Socket("127.0.0.1", port); 11 in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 12 out = new PrintWriter(socket.getOutputStream(),true); 13 out.println("hello"); 14 out.println("world"); 15 out.println("end"); 16 17 System.out.println("send message success..."); 18 while(true){ 19 String res = in.readLine(); 20 if("".equals(res)||res==null){ 21 break; 22 } 23 System.out.println("the res is:"+res); 24 } 25 26 27 } catch (Exception e) { 28 e.printStackTrace(); 29 }finally{ 30 if(in!=null){ 31 try { 32 in.close(); 33 } catch (IOException e) { 34 e.printStackTrace(); 35 } 36 in = null; 37 } 38 if(out!=null){ 39 out.close(); 40 out= null; 41 } 42 if(socket!=null){ 43 try { 44 socket.close(); 45 } catch (IOException e) { 46 e.printStackTrace(); 47 } 48 socket =null; 49 } 50 } 51 52 } 53 54 }
java代碼實現socket接口通訊(堵塞I/O)