Java Soce

1.Server and client

server

我们经常需要关闭一些实例,比如server,所以我们使用这个接口,来实现自动关闭。

我们可以这样写,手动关闭server

public class Server {public static void main(String args[]){try {ServerSocket server = new ServerSocket(8080);//accept() will block the thread until the clint send a request// accept() will return a socket represent the clientSystem.out.println("connecting...");Socket socket1=server.accept();System.out.println("IP address:"+socket1.getInetAddress().getHostAddress());//If you do not close the server, the port will be occupied and you are not able to use the portserver.close();}catch(IOException e){e.printStackTrace();}}
}

也可以这样写进try catch语句,自动关闭:

public static void main(String args[]){try(ServerSocket server = new ServerSocket(8080)) {//accept() will block the thread until the clint send a request// accept() will return a socket represent the clientSystem.out.println("connecting...");Socket socket1=server.accept();System.out.println("IP address:"+socket1.getInetAddress().getHostAddress());//If you do not close the server, the port will be occupied and you are not able to use the port}catch(IOException e){e.printStackTrace();}}
}

try后括号里的内容需要实现autocloseable 接口。

client

import java.io.IOException;
import java.net.Socket;public class Client {public static void main(String[] args) {//if you run on your own computer, then you can use "localhost"//if you run in the local area network(LAN), use "ipconfig" to see your sourcetry(Socket socket = new Socket("localhost",8080)){//here is the same way as Server//socket should close and I write it in try block}catch(IOException e){e.printStackTrace();}}
}

先运行server,再运行client,server在client运行之前,会一直监听端口。

这实际上是tcp的握手过程,只不过java全部封装了。

接受多个client

用while循环就行了

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;public class Server {public static void main(String args[]){try(ServerSocket server = new ServerSocket(8080)) {//accept() will block the thread until the clint send a request// accept() will return a socket represent the clientSystem.out.println("connecting...");while (true){Socket socket1=server.accept();System.out.println("IP address:"+socket1.getInetAddress().getHostAddress());}//If you do not close the server, the port will be occupied and you are not able to use the port}catch(IOException e){e.printStackTrace();}}
}

 这里的client和server是怎么联系的呢?

我们在client里创建了一个socket,给这个socket指定端口8080,然后我们在server里创建一个

ServerSocket,通过监听8080端口来连接这个socket。同时,把这个监听到的socket又通过accept接受为一个本地的socket,在例子里命名为socket1.这个本地化的socket1其实和client里的socket是连接的,但是名字可以不一样。
  1. server.accept():这是在服务器端Socket编程中的一种操作,其中server是一个ServerSocket对象。ServerSocket对象通常在服务器端用于监听特定的网络端口,以便接受客户端的连接请求。accept()方法是一个阻塞调用,它会等待客户端的连接请求,一旦有客户端连接请求到达,它会接受这个连接请求,并返回一个新的Socket对象,该Socket对象代表与客户端建立的连接。

  2. Socket socket1=server.accept();:这行代码执行了accept()方法,并将返回的Socket对象存储在变量socket1中。这个socket1对象表示与一个特定客户端建立的连接,可以使用它进行双向通信,即从客户端接收数据和向客户端发送数据。

2.客户端发送数据

client

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;public class Client {public static void main(String[] args) {//if you run on your own computer, then you can use "localhost"//if you run in the local area network(LAN), use "ipconfig" to see your sourcetry(Socket socket = new Socket("localhost",8080);Scanner scanner=new Scanner(System.in)){ //Scanner also need to close, so write scanner in try blockSystem.out.println("Already connected to the server!");System.out.println("write something that I can send to server:");//this is a convert stream// it is more convenient than socket.getOutputStream()OutputStreamWriter writer=new OutputStreamWriter(socket.getOutputStream());writer.write(scanner.nextLine()+"\n");//flush and client will send it to serverwriter.flush();//here is the same way as Server, "socket" should close and I write it in try blockSystem.out.println("data already sent");}catch(IOException e){System.out.println("fail to connect to server");e.printStackTrace();}}
}

注意

OutputStreamWriter writer=new OutputStreamWriter(socket.getOutputStream());
writer.write(scanner.nextLine()+"\n");

这行代码创建了一个OutputStreamWriter对象,该对象连接到给定的套接字(socket)的输出流,以便将字符数据写入该套接字所以我可以向OutputStreamWriter写入数据,写的数据会被放到套接字(socket)的输出流。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;public class Server {public static void main(String args[]){try(ServerSocket server = new ServerSocket(8080);) {//accept() will block the thread until the clint send a request// accept() will return a socket represent the clientSystem.out.println("connecting...");while (true){Socket socket1=server.accept();System.out.println("IP address:"+socket1.getInetAddress().getHostAddress());System.out.println("reading data...");//BufferedReader easy to output the dataBufferedReader reader=new BufferedReader(new InputStreamReader(socket1.getInputStream()));//socket need to close and did not write in try block//so need to close hereSystem.out.println(reader.readLine());socket1.close();}//If you do not close the server, the port will be occupied and you are not able to use the port}catch(IOException e){e.printStackTrace();}}
}

同理

BufferedReader reader=new BufferedReader(new InputStreamReader(socket1.getInputStream()));

这行代码创建了一个BufferedReader对象,该对象连接到给定的套接字(socket1)的输入流,以便以字符流的方式从套接字中读取数据

 

3.服务端发送数据

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/127433.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

面向对象设计——装饰模式

装饰模式(Decorator Pattern)是一种结构型设计模式,它允许你动态地为对象添加额外的功能,而不需要修改其源代码。这种模式属于设计模式中的包装模式,它通过将对象包装在装饰器类中来实现。 装饰模式的核心思想是以透明…

panabit日志审计singleuser_action.php任意用户添加漏洞复现

文章目录 panabit日志审计singleuser_action.php任意用户添加漏洞复现0x01 前言0x02 漏洞描述0x03 影响版本0x04 漏洞环境0x05 漏洞复现1.访问漏洞环境2.构造POC3.复现 panabit日志审计singleuser_action.php任意用户添加漏洞复现 0x01 前言 免责声明:请勿利用文章…

flutter之bloc使用详解

flutter中一切皆为Widget,因此在我们开发中,往往业务和UI逻辑写在一起,这样不利于代码维护,因此状态管理框架久诞生了,这篇就开始讲一讲Bloc。 对于Bloc库有两个,如下图: flutter_bloc其实是对…

Ubuntu连不上WiFi 或者虽然能连上校园网,但是浏览器打不开登录页面

写在前面 自己的电脑环境: Ubuntu20.04 一、问题描述 自己的 Ubuntu 遇到连接不上 除校园网之外的其他WiFi, 或者 虽然能连上校园网,但是浏览器打不开登录页面的问题。 二、解决方法 出现这种问题的原因可能是 之前开过VPN, 导致系统的网络设置出现…

网络编程中关于UDP套接字的一些知识点

关于UDP的介绍: UDP(User Datagram Protocol,用户数据报协议)是一种面向无连接的、不可靠的传输协议,它在网络编程中也起着重要的作用。 1. 低延迟:相比于TCP,UDP没有建立连接和拥塞控制的开销…

系统架构设计师历年真题案例知识点汇总

常见的软件质量属性有多种,例如性能(Performance)、可用性(Availability)、可靠性(Reliability)、健壮性(Robustness)、安全性(Security)、可修改性(Modification)、可变性(Changeability)、易用…

MATLAB算法实战应用案例精讲-【图像处理】姿态估计

目录 前言 算法原理 姿态估计 2D姿态估计 3D姿态估计 3D形态估计 应用案例

1-性能分析-android-systrace

1-性能分析-android-systrace 一:Systrace简介二: Systrace 简单使用1> Systrace.py 介绍1. Systrace.py -h2. 常用参数2> 查看TAG三:systrace html 线程状态查看1> 线程状态-绿色 : 运行中(Running)2> 线程状态-蓝色 : 可运行(Runnable)3> 线程状态-白色…

CSS3网页布局基础

CSS布局始于第2个版本,CSS 2.1把布局分为3种模型:常规流、浮动、绝对定位。CSS 3推出更多布局方案:多列布局、弹性盒、模板层、网格定位、网格层、浮动盒等。本章重点介绍CSS 2.1标准的3种布局模型,它们获得所有浏览器的全面、一致…

基于深度学习的自动驾驶汽车语义分割与场景标注算法研究。

自动驾驶汽车是当前研究的热点领域之一,其中基于深度学习的语义分割与场景标注算法在自动驾驶汽车的视觉感知中具有重要作用。本文将围绕自动驾驶汽车的语义分割与场景标注算法展开研究。 一、研究背景 随着人工智能技术的不断发展,自动驾驶汽车逐渐成…

Golang 编译原理

简介 Golang(Go语言)是一种开源的编程语言,由Google开发并于2009年首次发布。它具备高效、可靠的特性,被广泛应用于云计算、分布式系统、网络服务等领域。Golang的编译原理是理解和掌握这门语言的重要基础之一。本文将介绍Golang…

回归预测 | Matlab实现POA-CNN-SVM鹈鹕算法优化卷积神经网络-支持向量机多变量回归预测

Matlab实现POA-CNN-SVM鹈鹕算法优化卷积神经网络-支持向量机多变量回归预测 目录 Matlab实现POA-CNN-SVM鹈鹕算法优化卷积神经网络-支持向量机多变量回归预测效果一览基本介绍程序设计参考资料 效果一览 基本介绍 1.POS-CNN-SVM鹈鹕算法优化卷积神经网络-支持向量机的多变量回归…

将有序数组转换为二叉搜索树

做这一题的前提是要搞懂一些概念,比如什么是高度平衡的二叉树?什么又是搜索树? 二叉搜索树(Binary Search Tree) 它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则…

CV计算机视觉每日开源代码Paper with code速览-2023.10.31

精华置顶 墙裂推荐!小白如何1个月系统学习CV核心知识:链接 点击CV计算机视觉,关注更多CV干货 论文已打包,点击进入—>下载界面 点击加入—>CV计算机视觉交流群 1.【基础网络架构】(NeurIPS2023)Fa…

EVM6678L 开发教程: IBL-TFTP 引导 elf 文件

目录 EVM6678L 开发教程: IBL-TFTP 引导 elf 文件安装 Tftpd64测试工程测试说明 EVM6678L 开发教程: IBL-TFTP 引导 elf 文件 参考: "C:\ti\mcsdk_2_01_02_06\tools\boot_loader\examples\i2c\tftp\docs\README.txt" 此教程介绍如何在 EVM6678L 开发板上实现 IBL-…

uni-starter 使用常见问题

1. Invalid uni-id config file 没有找到uni-id文件导致 需要在uniCloud-aliyun/cloudfunctions/common/uni-config-center/uni-id/下新建 config.json 如果没有uni-id 就新建一个。 注意:config.json是一个标准json文件,不支持注释 uni-starter 按照…

树形结构数据展示及返回上一级

11月1日&#xff0c;又是搬砖的一天&#xff0c;让我们红尘作伴&#xff0c;活的潇潇洒洒。。。。。。 html <template><view class"content"><view><input class"sreachTool" v-model"toolValue"/><van-icon name…

进口跨境电商商城源码(海关179接口+海关报关+三单对碰)

海关179接口 现如今&#xff0c;跨境电商正在飞速发展&#xff0c;进口商品成为人们消费的热点。然而&#xff0c;进口商品的报关手续繁琐&#xff0c;而海关179接口的出现解决了这个问题。海关179接口是指与海关电子数据交换的商业接口&#xff0c;可以实现与海关进行数据对接…

Centos7上安装 Node.js

文章目录 一、前言二、步骤三、涉及nodejs&#xff0c;centos还是少用吧 一、前言 centos7安装nodejs如果直接安装较高版本会包错误&#xff0c;无法运行npm node: /lib64/libm.so.6: version GLIBC_2.27‘ not found (required by node)二、步骤 网上说的下载升级编译器的方…

PyTorch入门学习(十一):神经网络-线性层及其他层介绍

一、简介 神经网络是由多个层组成的&#xff0c;每一层都包含了一组权重和一个激活函数。每层的作用是将输入数据进行变换&#xff0c;从而最终生成输出。线性层是神经网络中的基本层之一&#xff0c;它执行的操作是线性变换&#xff0c;通常表示为&#xff1a; y Wx b其中…