天天看點

基于Socket的TCP網絡程式設計基于Socket的TCP程式設計

基于Socket的TCP程式設計

Java語言的基于套接字程式設計分為服務端程式設計和用戶端程式設計,其通信模型如圖所示:

基于Socket的TCP網絡程式設計基于Socket的TCP程式設計

用戶端Socket的工作過程

  1. 建立Socket對象,指明伺服器端的ip和端口号。
  2. 擷取一個輸出流,用于輸出資料。
  3. 寫出資料的操作。
  4. 資源的關閉。

伺服器端ServerSocket的工作過程

  1. 建立伺服器端的ServerSocket,指明自己的端口号。
  2. 調用accept()表示接收來自于用戶端的socket。
  3. 擷取輸入流。
  4. 讀取輸入流中的資料。
  5. 關閉資源。

示例一:用戶端發送資訊給服務端,服務端将資料顯示在控制台上。

@Test
    public void client(){
        Socket socket = null;
        OutputStream outputStream = null;
        try {
        	// 1. 建立Socket對象,指明伺服器端的ip和端口号。
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            socket = new Socket(inetAddress,8088);
            // 2. 擷取一個輸出流,用于輸出資料。
            outputStream = socket.getOutputStream();
            // 3. 寫出資料的操作。
            outputStream.write("用戶端發送消息".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        	// 4. 資源的關閉
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
    @Test
    public void server(){
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
        	//1.建立伺服器端的ServerSocket,指明自己的端口号
            serverSocket = new ServerSocket(8088);
			//2.調用accept()表示接收來自于用戶端的socket
            accept = serverSocket.accept();
			//3.擷取輸入流
            inputStream = accept.getInputStream();
			//4.讀取輸入流中的資料
            inputStreamReader = new InputStreamReader(inputStream,"utf-8");

//            //方式一:因為inputStream是位元組型輸入流,是以使用ByteArrayOutputStream解決亂碼問題
//            byteArrayOutputStream = new ByteArrayOutputStream();
//            byte[] buffer = new byte[5];
//            int len;
//            while ((len = inputStream.read(buffer)) != -1){
//                byteArrayOutputStream.write(buffer,0,len);
//
//            }
//            System.out.println(byteArrayOutputStream.toString());

            //方式二:使用轉換流inputStreamReader解決亂碼問題
            char[] cbuf = new char[5];
            int len;
            while ((len = inputStreamReader.read(cbuf)) != -1){
                String str = new String(cbuf,0,len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        	//5.關閉資源
            try {
                if (byteArrayOutputStream != null)
                    byteArrayOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (inputStreamReader != null)
                    inputStreamReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (accept != null)
                    accept.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (serverSocket != null)
                    serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
           

輸出結果:

基于Socket的TCP網絡程式設計基于Socket的TCP程式設計

示例二:用戶端發送檔案給服務端,服務端将檔案儲存在本地。

public class TCPTest2 {
    @Test
    public void client(){
        Socket socket = null;
        OutputStream outputStream = null;
        FileInputStream fileInputStream = null;
        BufferedInputStream bufferedInputStream= null;
        try {
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");

            socket = new Socket(inetAddress,8099);

            outputStream = socket.getOutputStream();

            fileInputStream = new FileInputStream(new File("04.PNG"));

            bufferedInputStream = new BufferedInputStream(fileInputStream);

            byte[] buffer = new byte[10];
            int len;
            while ((len = bufferedInputStream.read(buffer)) != -1){
                outputStream.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedInputStream != null)
                    bufferedInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fileInputStream != null)
                    fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    @Test
    public void server(){
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            serverSocket = new ServerSocket(8099);

            accept = serverSocket.accept();

            inputStream = accept.getInputStream();

            fileOutputStream = new FileOutputStream("08.PNG");

            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

            byte[] buffer = new byte[10];
            int len;
            while((len = inputStream.read(buffer)) != -1){
                bufferedOutputStream.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedOutputStream != null)
                    bufferedOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fileOutputStream != null)
                    fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (accept != null)
                    accept.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (serverSocket != null)
                    serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
           

示例三:從用戶端發送檔案給服務端,服務端儲存到本地。并傳回“發送成功”給用戶端。并關閉相應的連接配接。

public class TCPTest3 {
    @Test
    public void client(){
        Socket socket = null;
        OutputStream outputStream = null;
        FileInputStream fileInputStream = null;
        BufferedInputStream bufferedInputStream= null;
        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");

            socket = new Socket(inetAddress,8099);

            outputStream = socket.getOutputStream();

            fileInputStream = new FileInputStream(new File("04.PNG"));

            bufferedInputStream = new BufferedInputStream(fileInputStream);

            byte[] buffer = new byte[10];
            int len;
            while ((len = bufferedInputStream.read(buffer)) != -1){
                outputStream.write(buffer,0,len);
            }
            //關閉資料的輸出
            socket.shutdownOutput();

            //接收來自伺服器端的回報
            inputStream = socket.getInputStream();
            byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer1 = new byte[20];
            int len1;
            while ((len = inputStream.read(buffer)) != -1){
                byteArrayOutputStream.write(buffer,0,len);
            }
            System.out.println(byteArrayOutputStream.toString());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (byteArrayOutputStream != null)
                    byteArrayOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (bufferedInputStream != null)
                    bufferedInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fileInputStream != null)
                    fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    @Test
    public void server(){
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        OutputStream outputStream = null;
        try {
            serverSocket = new ServerSocket(8099);

            accept = serverSocket.accept();

            inputStream = accept.getInputStream();

            fileOutputStream = new FileOutputStream("09.PNG");

            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

            byte[] buffer = new byte[10];
            int len;
            while((len = inputStream.read(buffer)) != -1){
                bufferedOutputStream.write(buffer,0,len);
            }

            //伺服器端接收成功,給予用戶端回報
            outputStream = accept.getOutputStream();
            outputStream.write("資料已接收!".getBytes());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (bufferedOutputStream != null)
                    bufferedOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fileOutputStream != null)
                    fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (accept != null)
                    accept.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (serverSocket != null)
                    serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}