1. 程式人生 > >最簡單實現socket程式設計案例

最簡單實現socket程式設計案例

服務端實現多執行緒接收請求,在接受到客戶端的訊息後列印訊息並回送訊息長度給客戶端

客戶端實現鍵盤輸入併發送訊息給服務端

Server.class

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 socket = new ServerSocket(2000);

        System.out.println("伺服器準備就緒");
        System.out.println("伺服器資訊:" + socket.getLocalSocketAddress() + "Port: " + socket.getLocalPort());

        //等待客戶端連線
        for(;;){
            //得到客戶端
            Socket client = socket.accept();
            //客戶端構建非同步執行緒
            //啟動執行緒
            new Thread(new ClientHandler(client)).start();
        }

    }

    /**
     * 客戶端訊息處理
     */
    private static class ClientHandler implements Runnable{
        private Socket socket;
        private boolean flag = true;

        ClientHandler(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {
            System.out.println("新客戶端連線:" + socket.getInetAddress() + "Port: " + 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() + "Port: " + socket.getPort());
            }
        }
    }
}

Client.class

import java.io.*;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.net.Socket;

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

        socket.connect(new InetSocketAddress(Inet4Address.getLocalHost(), 2000),3000);

        System.out.println("已發起對伺服器的連線");
        System.out.println("客戶端資訊:" + socket.getLocalAddress() + "Port:" + socket.getLocalPort());
        System.out.println("伺服器資訊:" + socket.getInetAddress() + "Port:" + socket.getPort());

        try {
            todo(socket);
        }catch (Exception e){
            System.out.println("異常關閉");
        }finally {
            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輸出流,並轉換成列印流
        PrintStream printStream = new PrintStream(client.getOutputStream());

        //得到socket輸入流
        BufferedReader socketInput = new BufferedReader(new InputStreamReader(client.getInputStream()));

        boolean flag = true;
        do {
            //從鍵盤讀取併發送
            String str = input.readLine();
            printStream.println(str);

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

        input.close();
        printStream.close();
        socketInput.close();
    }
}