关于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();
				}
			}
		}
		

	}

}

 工程:

 运行结果:

原文地址:https://www.cnblogs.com/ths0201/p/java.html