标签:
传输控制协议(Transmission Control Protocol, TCP)是一种面向连接(连接导向)的、可靠的、基于字节流的运输层(Transport layer)通信协议,由IETF的RFC 793说明(specified)。(from bing)
2、TCP program:
(1)、有明确的C/S之分,Server端用ServerSocket,Client端用Socke;
(2)、Server端用accept()做監聽等待接收,一旦有鏈接連上的話,返回一個Socket對象作爲Client
(3)、C/S都是用getInputStream/getOutputStream來讀取/寫入message
下面上代碼:
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 import java.io.PrintWriter; 5 import java.net.ServerSocket; 6 import java.net.Socket; 7 8 public class ServerCode { 9 private static int port =4444; 10 static Socket cs; 11 public static void main(String[] args) throws IOException { 12 ServerSocket ss=new ServerSocket(port); 13 cs=ss.accept(); 14 System.out.println("Accept :"+cs); 15 try{ 16 BufferedReader br=new BufferedReader(new InputStreamReader(cs.getInputStream())); 17 PrintWriter pr=new PrintWriter(cs.getOutputStream(),true); 18 while(true){ 19 String str=br.readLine(); 20 if(str.equals("bye")){ 21 break; 22 } 23 System.out.println("Client->Server:"+str); 24 pr.println("send back to client:"+str); 25 } 26 br.close(); 27 pr.close(); 28 }catch(Exception e){ 29 System.out.println("error:"+e); 30 }finally{ 31 System.out.println("close the Server socket and the io."); 32 cs.close(); 33 ss.close(); 34 } 35 36 } 37 38 }
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 import java.io.PrintWriter; 5 import java.net.InetAddress; 6 import java.net.Socket; 7 8 public class ClientCode { 9 public static void main(String[] args) throws IOException { 10 InetAddress add=InetAddress.getByName("localhost"); 11 Socket cs=new Socket(add,4444); 12 System.out.println("socket = " + cs); 13 try{ 14 BufferedReader br=new BufferedReader(new InputStreamReader(cs.getInputStream())); 15 PrintWriter pw=new PrintWriter(cs.getOutputStream(),true); 16 pw.println("Hello I‘m qixi"); 17 String str=br.readLine(); 18 System.out.println(str); 19 pw.println("bye"); 20 }catch(Exception e){ 21 System.out.println(e); 22 }finally{ 23 System.out.println("close the Client socket and the io."); 24 cs.close(); 25 } 26 } 27 }
Java study 2:The note of studying Socket which based TCP
标签:
原文地址:http://www.cnblogs.com/qixi233/p/4418238.html