六、网络编程
# 六、网络编程
# 1、windows系统的 端口检测 工具 tcping
下载地址 :https://download.elifulkerson.com//files/tcping/0.39/tcping.exe (opens new window)
把 tcping.exe 工具放到目录 C:\Windows\System32下
打开控制台
使用方式 tcping ip 端口
这个工具类似于 linux系统上的 telnet工具 可以帮助我们在Windows系统上检测 远程端口的连通性
# 2、基于TCP协议的Socket(客户端)和ServerSocket(服务端)
Java的Socket是Java语言提供的一种用于网络通信的机制。它基于TCP/IP协议,允许应用程序通过网络进行数据交换。
Socket允许客户端和服务器之间建立连接,并在连接上进行数据传输。
Java中的Socket编程涉及两种基本类型:服务器Socket(ServerSocket)和客户端Socket(Socket)。
服务器Socket用于服务器端,监听客户端的连接请求并接受连接,而客户端Socket用于客户端,发起连接并与服务器通信。
简单的代码示例: 这个代码可以结合 上面的 NIO Selector 实现的群聊Demo 对比一下
使用 Java NIO提供的 ServerSocketChannel实现的服务端 仅使用单个线程就可以处理多个客户端连接
下面的ServerSocket 为了管理每个客户端连接 必须使用多线程为每个客户端连接都创建一个线程
服务端
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerDemo {
public static void main(String[] args) {
//创建服务器Socket对象
int port = 18848;
try (ServerSocket ss = new ServerSocket(port)) {
while (true) {
//监听客户端连接,返回一个对应的Socket对象
Socket s = ss.accept();
//为每一个客户端开启一个线程
new Thread(() -> {
try (InputStream inputStream = s.getInputStream();
OutputStream outputStream = s.getOutputStream();
BufferedWriter bwServer = new BufferedWriter(new OutputStreamWriter(outputStream));) {
//接收数据写到文本文件
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String str = br.readLine();
while (str != null) {
// 打印客户端输入的内容
System.out.println(str);
//给出反馈
bwServer.write("Accept Successfully!");
bwServer.newLine();
bwServer.flush();
str = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
客户端A
import java.io.*;
import java.net.Socket;
public class ClientA {
public static void main(String[] args){
//创建客户端Socket对象
try (Socket s = new Socket("127.0.0.1", 18848);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader sbr = new BufferedReader(new InputStreamReader(s.getInputStream()));){
String line;
while ((line = br.readLine()) != null) {
bw.write("客户端A:"+line);
bw.newLine();
bw.flush();
// 新增:读取并打印服务器反馈
String serverResponse = sbr.readLine();
if (serverResponse != null) {
System.out.println("服务器反馈:" + serverResponse);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
客户端B
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class ClientB {
public static void main(String[] args){
//创建客户端Socket对象
try (Socket s = new Socket("127.0.0.1", 18848);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader sbr = new BufferedReader(new InputStreamReader(s.getInputStream()));){
String line;
while ((line = br.readLine()) != null) {
bw.write("客户端B:"+line);
bw.newLine();
bw.flush();
// 新增:读取并打印服务器反馈
String serverResponse = sbr.readLine();
if (serverResponse != null) {
System.out.println("服务器反馈:" + serverResponse);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
演示效果如下:
# 3、 基于UDP协议的DatagramSocket
简单代码示例:
服务端:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class AAA {
public static void main(String[] args) {
int port = 18848;
try (DatagramSocket serverSocket = new DatagramSocket(port);) {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
byte[] sendBuffer;
while (true) {
// 接收数据
serverSocket.receive(packet);
String message = new String(packet.getData(), 0, packet.getLength());
System.out.println(message);
// 准备回复消息并发送
String replyMessage = "收到消息: " + message;
sendBuffer = replyMessage.getBytes();
InetAddress clientAddress = packet.getAddress();
int clientPort = packet.getPort();
DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, clientAddress, clientPort);
serverSocket.send(sendPacket);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
客户端
class ClientAAA {
public static void main(String[] args) throws IOException {
String hostname = "localhost";
int port = 18848;
try (DatagramSocket clientSocket = new DatagramSocket();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));) {
InetAddress address = InetAddress.getByName(hostname);
String s = "";
while ((s = bufferedReader.readLine()) != null) {
byte[] buffer = s.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, port);
clientSocket.send(packet);
// 接收服务器的回复
byte[] receiveBuffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
clientSocket.receive(receivePacket);
String serverReply = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println(serverReply);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行结果: