1. 程式人生 > >ServerSocket(TCP/IP協議)__Java

ServerSocket(TCP/IP協議)__Java

accep sock 成功 服務器 命令 dos ioe println inpu

服務器端  
 1     public static void main(String[] args) throws IOException {
 2         System.out.println("服務器開啟監聽");
 3         ServerSocket server=new ServerSocket(6666);
 4         Socket client = server.accept();
 5         System.out.println("連接成功");
 6         while(true){//循環接收
 7             byte
[] data=new byte[1024]; 8 int count = client.getInputStream().read(data); 9 String msg= new String(data,0,count,"utf-8"); 10 if("exit".equals(msg)) 11 break; 12 else 13 System.out.println(msg); 14 } 15 client.close();
16 server.close(); 17 }
用戶端
 1     public static void main(String[] args) throws UnknownHostException, IOException {
 2         System.out.println("客戶端開始訪問");        
 3         Socket client = new Socket("1.1.1.1", 6666);//參數為需要ServerSocket服務器的:IP 和 端口號,端口號是ServerSocket服務器設的端口號
 4
     Scanner scanner = new Scanner(System.in);
5
     while(true){//循環發送
6
       System.out.println("請輸入:");
7
       String x=scanner.next();
8
       byte[] data=x.getBytes("utf-8");
9
      client.getOutputStream().write(data);
10        if("end".equals(x))
11        break;
12     }
13     client.close();
14   }
測試方法:

  建兩個有main方法的類,把代碼分別放入類中。可以在cmd中用dos命令啟動兩個類,也可以用tomcate啟動。(註:先啟動服務器端的main方法再啟動用戶端的代碼)

ServerSocket(TCP/IP協議)__Java