1. 程式人生 > >TCP網路程式設計經典案列

TCP網路程式設計經典案列

伺服器端

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

public class Exercise25_1 {
    public static void main(String[] args)throws Exception{
        ServerSocket server = new ServerSocket(8888);
        Socket client = null;
        boolean flag = true;
        while(flag){
            System.out.println("等待連線");
            client = server.accept();
            BufferedReader buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
            PrintStream pout = new PrintStream(client.getOutputStream());
            boolean temp=true;
            while (temp){
                String str =buf.readLine();
                if(str == null||"".equals(str)){
                    temp=false;
                    break;
                }
                if ("bye".equals(str)){
                    temp=false;
                    break;
                }
                pout.println("客戶端:"+str);
            }
            pout.close();
            client.close();
            flag=false;
        }
        server.close();
    }
}

客戶端

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

public class Exercise25_2 {
    public static void main(String[] args)throws Exception{
        Socket client = new Socket("localhost",8888);
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        BufferedReader buf = null;
        buf=new BufferedReader(new InputStreamReader(client.getInputStream()));
        PrintStream out = new PrintStream(client.getOutputStream());
        boolean flag=true;
        while(flag){
            System.out.println("請輸入");
            String str =input.readLine();
            if(str==null||"".equals(str)){
                flag=false;
                break;
            }
            if ("bye".equals(str)){
                flag=false;
                break;
            }
            out.println(str);
            System.out.println(buf.readLine());
        }
        client.close();
    }
}