關於java中C/S架構,創建服務器和客戶端


                                                                                         初學關於java中 C/S架構配置

概述C/S: Client/Server 架構,即服務器/客戶端架構。通過將任務合理分配到 Client 端和 Server 端,降低了系統的通訊開銷,需要安裝客戶端才可進行管理操作。

優點:
1) 界面和操作可以很豐富。
2) 大部分數據保存在客戶端,相對安全。
3) 大部分功能都集成在客戶端, 只需從服務器下載少量數據, 因此訪問
速度較快。
缺點
1) 升級維護工作量較大,每一個客戶端都需要升級。
2) 用戶群固定。由於程序需要安裝才可以使用,因此不適合面向一些不
可知的用戶。

創建服務器:

 

package com.bjpowernode.scoket;

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

public class MyServerSocket {

	/**
	 * 創建服務器端
	 * @param args
	 */
	public static void main(String[] args) {
		ServerSocket serverSocket = null;
		Socket clientSocket = null;
		BufferedReader br = null;
		
		try {
			//創建服務端套接字,並且綁定端口號
			serverSocket = new ServerSocket(8080);
			//開始監聽網絡,此時程序處於等待狀態,接受客戶端的消息
			clientSocket = serverSocket.accept();
			//接收消息
			br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
			//打印消息
			String temp = null;
			while((temp = br.readLine()) != null){
				System.out.println(temp);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			//關閉資源
			if(br != null){
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			if(clientSocket != null){
				try {
					clientSocket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(serverSocket != null){
				try {
					serverSocket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

}

 

 創建客戶端:

package com.bjpowernode.scoket;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class MySocket {

	/**
	 * 創建客戶端
	 * @param argss
	 */ 
	public static void main(String[] args) {
		Socket clientSocket = null;
		PrintWriter out = null;
		
		try {
			//創建客戶端套接字,綁定IP地址和端口號
			clientSocket = new Socket("localhost",8080);
			//創建輸出流對象
			out = new PrintWriter(clientSocket.getOutputStream());
			//發送消息
			String msg = "Hello Word";
			out.print(msg);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			if(out != null){
				out.close();
			}
			if(clientSocket != null){
				try {
					clientSocket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		

	}

}

 工程:

 運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM