在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
初学关于java中 C/S架构配置 概述C/S: Client/Server 架构,即服务器/客户端架构。通过将任务合理分配到 Client 端和 Server 端,降低了系统的通讯开销,需要安装客户端才可进行管理操作。 优点: 创建服务器:
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(); } } } } } 工程: 运行结果:
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论