1. 程式人生 > >java的基於TCP的Socket程式設計

java的基於TCP的Socket程式設計

主要用到Socket類。new一個Socket類指定連線的伺服器和埠號

void sock1(){
        System.out.println("客戶端");
        try {
            Socket socket=new Socket("localhost",8800);
            InputStream is=socket.getInputStream();
            OutputStream os=socket.getOutputStream();
            String str="說句假話,我好愛你呀。"
;//中文一般用位元組流,方便修改編碼方式 os.write(str.getBytes()); socket.close(); } catch (IOException e) { e.printStackTrace(); } }

伺服器需要new一個serverSocket指定埠號
呼叫serverSocket.accept()生成Socket物件

void run17() {
        System.out.println("伺服器");
        try {
            ServerSocket serverSocket = new
ServerSocket(8800); Socket accept = serverSocket.accept(); InputStream is = accept.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is));//緩衝區存接受到的位元組碼 int n; String str = ""; while ((str = br.readLine()) != null
) {//逐行讀取 System.out.println(str); } serverSocket.close(); accept.close(); } catch (IOException e) { e.printStackTrace(); } }