1. 程式人生 > 其它 >socket 實現TCP通訊 的客戶端和服務端

socket 實現TCP通訊 的客戶端和服務端

服務端:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;


public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new
ServerSocket(2000); System.out.println("伺服器準備就緒~"); System.out.println("伺服器資訊:" + server.getInetAddress() + " P:" + server.getLocalPort()); // 等待客戶端連線 for (; ; ) { // 得到客戶端 Socket client = server.accept(); // 客戶端構建非同步執行緒 ClientHandler clientHandler = new
ClientHandler(client); // 啟動執行緒 clientHandler.start(); } } /** * 客戶端訊息處理 */ private static class ClientHandler extends Thread { private Socket socket; private boolean flag = true; ClientHandler(Socket socket) {
this.socket = socket; } @Override public void run() { super.run(); System.out.println("新客戶端連線:" + socket.getInetAddress() + " P:" + socket.getPort()); try { // 得到列印流,用於資料輸出;伺服器回送資料使用 PrintStream socketOutput = new PrintStream(socket.getOutputStream()); // 得到輸入流,用於接收資料 BufferedReader socketInput = new BufferedReader(new InputStreamReader( socket.getInputStream())); do { // 客戶端拿到一條資料 String str = socketInput.readLine(); if ("bye".equalsIgnoreCase(str)) { flag = false; // 回送 socketOutput.println("bye"); } else { // 列印到螢幕。並回送資料長度 System.out.println(str); socketOutput.println("回送:" + str.length()); } } while (flag); socketInput.close(); socketOutput.close(); } catch (Exception e) { System.out.println("連線異常斷開"); } finally { // 連線關閉 try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("客戶端已退出:" + socket.getInetAddress() + " P:" + socket.getPort()); } } }

客戶端:

package com.tan;

import java.io.*;
import java.net.*;


public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket();
        // 超時時間
        socket.setSoTimeout(3000);

        // 連線本地,埠2000;超時時間3000ms
        socket.connect(new InetSocketAddress(Inet4Address.getLocalHost(), 2000), 3000);

        System.out.println("已發起伺服器連線,並進入後續流程~");
        System.out.println("客戶端資訊:" + socket.getLocalAddress() + " P:" + socket.getLocalPort());
        System.out.println("伺服器資訊:" + socket.getInetAddress() + " P:" + socket.getPort());

        try {
            // 傳送接收資料
            todo(socket);
        } catch (Exception e) {
            System.out.println("異常關閉");
        }

        // 釋放資源
        socket.close();
        System.out.println("客戶端已退出~");

    }

    private static void todo(Socket client) throws IOException {
        // 構建鍵盤輸入流
        InputStream in = System.in;
        BufferedReader input = new BufferedReader(new InputStreamReader(in));


        // 得到Socket輸出流,並轉換為列印流
        OutputStream outputStream = client.getOutputStream();
        PrintStream socketPrintStream = new PrintStream(outputStream);


        // 得到Socket輸入流,並轉換為BufferedReader
        InputStream inputStream = client.getInputStream();
        BufferedReader socketBufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        boolean flag = true;
        do {
            // 鍵盤讀取一行
            String str = input.readLine();
            // 傳送到伺服器
            socketPrintStream.println(str);


            // 從伺服器讀取一行
            String echo = socketBufferedReader.readLine();
            if ("bye".equalsIgnoreCase(echo)) {
                flag = false;
            }else {
                System.out.println(echo);
            }
        }while (flag);

        // 資源釋放
        socketPrintStream.close();
        socketBufferedReader.close();

    }


}

  

服務端:

客戶端:

本文來自部落格園,作者:qiaoerwa,轉載請註明原文連結:https://www.cnblogs.com/qiaoerwa/p/15434838.html