1. 程式人生 > >Java開發練習9.2 TCP

Java開發練習9.2 TCP

使用TCP協議編寫一個網路程式,設定伺服器端的監聽埠是8002,當與客戶端建立連線後,伺服器端向客戶端傳送資料“Hello,world”,客戶端收到資料後列印輸出。

public class tcp {  
  
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
        try{  
            ServerSocket s = new ServerSocket(8002);  
            while(true){  
                Socket s1 = s.accept();  
                OutputStream os = s1.getOutputStream();  
                DataOutputStream dis = new DataOutputStream(os);  
                dis.writeUTF("Hello,wrold!");  
                dis.close();  
                s1.close();  
            }             
  
        }catch(Exception e){  
            e.printStackTrace();  
        }  
    }  
  
}  
   
public class tcpclient {  
  
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
        try{  
            Socket s1 = new Socket("127.0.0.1", 8002);  
            InputStream is = s1.getInputStream();  
            DataInputStream dos= new DataInputStream(is);  
            System.out.println(dos.readUTF());  
            dos.close();  
            s1.close();  
        }catch(Exception e){  
            e.printStackTrace();  
        }  
    }  
  
}