网络编程基本知识与实践(二)
(一)中已经把大致环境搭建完成了,接下来我们需要让客户端不停访问服务器,首先思路是让这一段代码不断循环,同时streamUtils.closeStream();注释掉这一行,不关闭流:
public void connect(){
try {
Socket client = new Socket(this.IP,this.port);
PrintUtil.clientPrint("服务器连接成功");
StreamUtils streamUtils = new StreamUtils(client);
while (true){
streamUtils.write("Client");
PrintUtil.clientPrint("发送完完数据");
streamUtils.readAndprint();
PrintUtil.clientPrint("接受信息完毕!");
}
// streamUtils.closeStream();
} catch (IOException e) {
e.printStackTrace();
}
}
服务器在执行Socket client = serverSocket.accept();就处于阻塞状态了。因为这个accept()方法只能接收新的套接字,所以我们可以修改客户端,每次请求一次就新建一个socket,用完就关闭流。
public void connect(){
try {
while (true) {
Socket client = new Socket(this.IP, this.port);
PrintUtil.clientPrint("服务器连接成功");
StreamUtils streamUtils = new StreamUtils(client);
streamUtils.write("Client");
PrintUtil.clientPrint("发送完完数据");
streamUtils.readAndprint();
PrintUtil.clientPrint("接受信息完毕!");
streamUtils.closeStream();
}
} catch (IOException e) {
e.printStackTrace();
}
}
这样就解决了刚才的问题。
但这样很不安全,每次访问中间都存在间隙,这样就给坏人拦截我们信息的机会,所以我们希望我们能连上就不要断开,可以一直与服务器保持联系,这时候我们就需要把服务器上处理与发送消息的那段代码放到子线程中
服务器端:
public void start(){
try {
//创建对象,对象的属性和方法调用(API学习核心内容)
ServerSocket serverSocket = new ServerSocket(this.port);
PrintUtil.serverPrint("端口开放成功");
while (true){
PrintUtil.serverPrint("调用方法准备接受连接");
//每个客户端都有一个独立的空间
Socket client = serverSocket.accept();//接收客户端连接,一次客户端的连接套接字
System.out.println(client.getInetAddress());
final StreamUtils streamUtils = new StreamUtils(client);
Thread thread = new Thread(){
@Override
public void run() {
try {
while (true) {
streamUtils.readAndprint();
PrintUtil.serverPrint("接收完数据");
streamUtils.write("Server");
PrintUtil.serverPrint("发送完数据");
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
thread.start();
// streamUtils.closeStream();
}
} catch (IOException e) {
e.printStackTrace();
PrintUtil.serverPrint("端口开发失败");
}
}
客户端:
public void connect(){
try {
Socket client = new Socket(this.IP, this.port);
PrintUtil.clientPrint("服务器连接成功");
while (true) {
StreamUtils streamUtils = new StreamUtils(client);
streamUtils.write("Client");
PrintUtil.clientPrint("发送完完数据");
streamUtils.readAndprint();
PrintUtil.clientPrint("接受信息完毕!");
// streamUtils.closeStream();
}
} catch (IOException e) {
e.printStackTrace();
}
}
就可以实现一次连接后多次收发数据。
本文介绍了一种通过不断循环实现客户端持续访问服务器的方法,并探讨了解决每次访问存在的间隙问题,确保信息安全,实现客户端与服务器间稳定的数据收发。
227

被折叠的 条评论
为什么被折叠?



