写点什么

实现服务器和客户端数据交互,Java Socket 有妙招

发布于: 刚刚

摘要:在 Java SDK 中,对于 Socket 原生提供了支持,它分为 ServerSocket 和 Socket。


本文分享自华为云社区《Java Socket 如何实现服务器和客户端数据交互》,作者: jackwangcumt 。

1 Socket 概述

根据百度百科的定义,Socket 译为套接字,它是对网络中不同主机上的应用进程之间进行双向通信的端点的抽象。一个 Socket 实例就是网络上进程通信的一端,提供了应用层进程利用网络协议交换数据的机制。Socket 向上连接各种应用进程,向下连接各种网络协议,是应用程序通过网络协议进行通信的接口。其示意图如下下图所示:

(来自《Java TCP/IP Socket 编程》)


从上图可知,套接字 Socket 在 OSI 七层模型中处于应用层和传输层之间,是一个重要的接口。一般来说,传输层协议有 TCP 协议和 UDP 协议。这两个协议底层都基于 IP 网络层协议。

2 Java Socket 实现

在 Java SDK 中,对于 Socket 原生提供了支持,它分为 ServerSocket 和 Socket,其中 ServerSocket 发起一个服务端的 Socket,其中需要提供一个端口号,如果给定 0,则自动申请可用的端口。当然了,也可以指定具体的端口号(有一定的范围,不超过 65535 )。不过这里需要注意,传入的端口不能被其他应用占用,否则启动服务失败。下面给出一个简单的 ServerSocket 示例,代码如下:

package com.example.demo.network;import java.io.IOException;import java.io.PrintWriter;import java.net.ServerSocket;import java.net.Socket;import java.util.Scanner;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class MyServer {    //<= 65535    private static final int PORT = 65535;
public static void main(String[] args) throws Exception {
try (ServerSocket listener = new ServerSocket(PORT)) { System.out.println("Server Started"); //线程池大小,它根据客户端数来决定,当大于10时,则之前的10个线程仍然可以工作, // 而超过的线程则进入队列中,等待。 //当之前的客户端释放量后,则在队列中的线程仍然可以工作。 ExecutorService pool = Executors.newFixedThreadPool(10); while (true) { //多线程 pool.execute(new MyServerDemo01(listener.accept())); System.out.println(pool); } } } //Runnable接口的实现对象可以被线程Thread调用 private static class MyServerDemo01 implements Runnable {
private Socket socket;
MyServerDemo01(Socket socket) { this.socket = socket; }
@Override public void run() { System.out.println("Client [" + socket.getRemoteSocketAddress().toString()+" ] Connected"); try { //输入 Scanner in = new Scanner(socket.getInputStream()); //输出 PrintWriter out = new PrintWriter(socket.getOutputStream(), true); while (in.hasNextLine()) { String msg = in.nextLine(); System.out.println("Client [" + socket.getRemoteSocketAddress().toString()+" ] : " + msg); out.println(msg.toUpperCase()); } } catch (Exception e) { System.out.println("Error:" + socket+ e.getMessage()); } finally { try { //关闭socket socket.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Closed: " + socket); } } }}
复制代码


启动该 Server 端,并开始监听客户端的连接。当客户端没有连接时,服务器线程池 pool 并未启动单独的线程。下面给出客户端的 Java Socket 实现,具体的示例代码如下:

package com.example.demo.network;import java.io.PrintWriter;import java.net.Socket;import java.util.Scanner;public class MyClient {    //<= 65535    private static final int PORT = 65535;    //服务器地址    private static final String IP = "127.0.0.1";
public static void main(String[] args) throws Exception {
try (Socket socket = new Socket(IP, PORT)) { System.out.println("Client ["+socket.getRemoteSocketAddress().toString()+" ] Started"); Scanner scanner = new Scanner(System.in); Scanner in = new Scanner(socket.getInputStream()); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); while (scanner.hasNextLine()) { out.println(scanner.nextLine()); System.out.println("Server Response:"+ in.nextLine()); } }catch (Exception ex){ System.out.println("Error : "+ ex.getMessage()); } }}
复制代码


从代码可知,try (Socket socket = new Socket(IP, PORT)) 是一种包含资源释放的 try-with-resource 机制,它会自动进行资源释放,而不需要手动进行释放。Socket 对象要想和服务器通信,必须要明确服务器的 IP 地址和端口,否则不能正确通信,Socket 启动时,也会在主机上占用自己的端口。我们首先启动 Server 端,然后可以同时启动 10 个以上的 Client 端,比如 13 个,那么超过 Executors.newFixedThreadPool(10)限定的数量 10 后,将进入 queued tasks 队列中进行排队等待。通过打印 pool 对象,可以看出当前的状态,比如[Running, pool size = 4, active threads = 4, queued tasks = 0, completed tasks = 0]说明当前在运行状态,线程池大小为 10,激活的线程为 10,等待的任务线程 queued tasks 为 0。


下面给出 Server 端相关输出示例:

Server Startedjava.util.concurrent.ThreadPoolExecutor@256216b3[Running, pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 0]Client [/127.0.0.1:64590 ] Connectedjava.util.concurrent.ThreadPoolExecutor@256216b3[Running, pool size = 2, active threads = 2, queued tasks = 0, completed tasks = 0]Client [/127.0.0.1:64597 ] Connectedjava.util.concurrent.ThreadPoolExecutor@256216b3[Running, pool size = 3, active threads = 3, queued tasks = 0, completed tasks = 0]Client [/127.0.0.1:64603 ] ConnectedClient [/127.0.0.1:64590 ] : helloClient [/127.0.0.1:64590 ] : helloClient [/127.0.0.1:64597 ] : worldClient [/127.0.0.1:64597 ] : worldClient [/127.0.0.1:64603 ] : pythonClient [/127.0.0.1:64597 ] : python02java.util.concurrent.ThreadPoolExecutor@256216b3[Running, pool size = 4, active threads = 4, queued tasks = 0, completed tasks = 0]Client [/127.0.0.1:57806 ] Connectedjava.util.concurrent.ThreadPoolExecutor@256216b3[Running, pool size = 5, active threads = 5, queued tasks = 0, completed tasks = 0]Client [/127.0.0.1:57814 ] Connectedjava.util.concurrent.ThreadPoolExecutor@256216b3[Running, pool size = 6, active threads = 6, queued tasks = 0, completed tasks = 0]Client [/127.0.0.1:57820 ] Connectedjava.util.concurrent.ThreadPoolExecutor@256216b3[Running, pool size = 7, active threads = 7, queued tasks = 0, completed tasks = 0]Client [/127.0.0.1:57827 ] Connectedjava.util.concurrent.ThreadPoolExecutor@256216b3[Running, pool size = 8, active threads = 8, queued tasks = 0, completed tasks = 0]Client [/127.0.0.1:57833 ] Connectedjava.util.concurrent.ThreadPoolExecutor@256216b3[Running, pool size = 9, active threads = 9, queued tasks = 0, completed tasks = 0]Client [/127.0.0.1:57839 ] Connectedjava.util.concurrent.ThreadPoolExecutor@256216b3[Running, pool size = 10, active threads = 10, queued tasks = 0, completed tasks = 0]Client [/127.0.0.1:57845 ] Connectedjava.util.concurrent.ThreadPoolExecutor@256216b3[Running, pool size = 10, active threads = 10, queued tasks = 1, completed tasks = 0]java.util.concurrent.ThreadPoolExecutor@256216b3[Running, pool size = 10, active threads = 10, queued tasks = 2, completed tasks = 0]java.util.concurrent.ThreadPoolExecutor@256216b3[Running, pool size = 10, active threads = 10, queued tasks = 3, completed tasks = 0]Closed: Socket[addr=/127.0.0.1,port=64590,localport=65535]Client [/127.0.0.1:57854 ] ConnectedClient [/127.0.0.1:57814 ] : t2Client [/127.0.0.1:57814 ] : tw2
复制代码

客户端相关输入输出界面如下:


Client [/127.0.0.1:65535 ] StartedworldServer Response:WORLDworldServer Response:WORLDpython02Server Response:PYTHON02
复制代码


点击关注,第一时间了解华为云新鲜技术~

发布于: 刚刚阅读数: 2
用户头像

提供全面深入的云计算技术干货 2020.07.14 加入

华为云开发者社区,提供全面深入的云计算前景分析、丰富的技术干货、程序样例,分享华为云前沿资讯动态,方便开发者快速成长与发展,欢迎提问、互动,多方位了解云计算! 传送门:https://bbs.huaweicloud.com/

评论

发布
暂无评论
实现服务器和客户端数据交互,Java Socket有妙招