1. 程式人生 > >實現ECHO的客戶端伺服器程式設計(多執行緒處理)

實現ECHO的客戶端伺服器程式設計(多執行緒處理)

伺服器的主要流程:

設定一個埠(ServerSocket)->客戶端連線(.accept())->獲得從客戶端來的資料流->將該資料流到輸出流中

客戶端的主要流程:

設定bufferreader輸入流->連線上埠->獲得從伺服器端來的資料流->將該資料流到輸出流中

->將客戶端從鍵盤輸入的資料寫入到輸出流中給伺服器

package com.mldn.servet;

import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * 實現伺服器端
 * 可以多執行緒
 * @author lenovo
 *
 */
public class EchoServr {
	private  static class ClientThread implements Runnable{
		private Socket client=null;//描述每一個不同的客戶端
		private Scanner scan=null;
		private PrintStream out=null;
		private boolean flag=true;
		public ClientThread(Socket client) throws Exception{
			this.client=client;
			this.scan=new Scanner(client.getInputStream());//獲得從客戶端哪裡獲得的資料到輸入流中
			//scan.useDelimiter("\n");
			this.out=new PrintStream(client.getOutputStream());//將資料到輸出流中
		}
     
		@Override
		public void run() {
			// TODO Auto-generated method stub
			while(this.flag) {
				if(scan.hasNext()) {//如果還有資料
					String val=scan.next().trim();//一定要加個trim()來去掉換行符
					if("byebye".equals(val)) {
						out.println("byebyebye...");
						this.flag=false;
					}else {
						out.println("[echo]"+val);
					}
				}
			}
			
			try {
				client.close();
				scan.close();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		  
		}
		
	}
	public static void main(String[] args) throws Exception {
		ServerSocket server=new ServerSocket(1234);
		System.out.println("等待客戶端連線");
		
		
		boolean flag=true;
		while(flag) {
			Socket client=server.accept();//有客戶端連線
			new Thread(new ClientThread(client)).start();
		}
		
		
	}

}
package com.mldn.servet;

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

/**
 *客戶端的編寫
 * @author lenovo
 *
 */
public class EchoClient {
	private static final BufferedReader KEYBOARD_INPUT=new BufferedReader(new InputStreamReader(System.in));
    public static void main(String[] args) throws Exception {
    	Socket client=new Socket("localhost",1234);
    	Scanner scan=new Scanner(client.getInputStream());
    	PrintStream out=new PrintStream(client.getOutputStream());
    	boolean flag=true;
    	while(flag) {
    		String input=getString("請輸入要傳送的內容:").trim();
    		out.println(input);//由於這裡用到了換行符,因此後面的服務端要用到trim()
    		if(scan.hasNext()) {
    			System.out.println(scan.next());
    		}
    		if("byebye".equals(input)) {
    			flag=false;
    		}
    	}
    	scan.close();
    	client.close();
    	out.close();
	
}
    public static String  getString(String prompt) throws Exception {
    	System.out.println(prompt);
    	String str=KEYBOARD_INPUT.readLine();
    	return str;
    	
    }
}

相關推薦

no