java实现socket从服务器连续获取消息的示例
时间:2021-10-22 02:50:55
服务器端我们用软件模拟,是一个很小巧的软件,下载软件NetAssist:http://xiazai.jb51.net/201403/tools/NetAssist(jb51.net).rar
第二步贴上我们客户端的代码:
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
public class Client {
public static final String IP_ADDR = "192.168.3.65";//服务器地址
public static final int PORT = 8080;//服务器端口号
static String text = null;
public static void main(String[] args) throws IOException {
System.out.println("客户端启动...");
Socket socket = null;
socket = new Socket(IP_ADDR, PORT);
while (true) {
try {
//创建一个流套接字并将其连接到指定主机上的指定端口号
//读取服务器端数据
DataInputStream input = new DataInputStream(socket.getInputStream());
byte[] buffer;
buffer = new byte[input.available()];
if(buffer.length != 0){
System.out.println("length="+buffer.length);
// 读取缓冲区
input.read(buffer);
// 转换字符串
String three = new String(buffer);
System.out.println("内容=" + three);
}
} catch (Exception e) {
System.out.println("客户端异常:" + e.getMessage());
}
}
}
}
可以看到打印结果如下:
length表示消息的长度
客户端启动...
length=27
内容=https://www.jb51.net
好了,一个socket客户端我们就完成了,这个是可以一直接收服务器发过来的消息的。
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Mybatis如何传入多个参数的实现代码
Java中常用缓存Cache机制的实现
Java BigDecimal使用方法详解
Spring注解@DependsOn解析
在idea中显示springboot面板的方法
![](https://img.aspxhome.com/file/2023/6/71846_0s.png)
SpringBoot整合RocketMQ的详细过程
![](https://img.aspxhome.com/file/2023/6/60256_0s.jpg)
Java VisualVM监控远程JVM(详解)
![](https://img.aspxhome.com/file/2023/8/61588_0s.jpg)
SpringBoot集成gRPC微服务工程搭建实践的方法
C#复制数组的两种方式及效率比较
![](https://img.aspxhome.com/file/2023/3/66133_0s.png)
Java spring的三种注入方式详解流程
![](https://img.aspxhome.com/file/2023/0/85910_0s.png)
Java实现常见排序算法的优化
SpringMVC框架实现图片上传与下载
![](https://img.aspxhome.com/file/2023/4/65204_0s.jpg)
Quarkus中ConfigSourceInterceptor的加密配置实现
C#向word文档插入新段落及隐藏段落的方法
![](https://img.aspxhome.com/file/2023/9/83269_0s.jpg)
Java单例模式的8种写法(推荐)
![](https://img.aspxhome.com/file/2023/4/76614_0s.png)
新手小白学JAVA IDEA下载使用手册全集
![](https://img.aspxhome.com/file/2023/3/59773_0s.jpg)
Java8中对于LocalDateTime的序列化和反序列化问题
简单分析Java的求值策略原理
![](https://img.aspxhome.com/file/2023/7/89637_0s.png)
Java中OAuth2.0第三方授权原理与实战
![](https://img.aspxhome.com/file/2023/4/70994_0s.jpg)
Java开发之Lombok指南
![](https://img.aspxhome.com/file/2023/2/64202_0s.jpg)