Socket通信(TCP+UDP)
程序员文章站
2022-07-07 15:40:58
...
一.TCP通信
TcpServer.java
package server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
private static final int PORT = 8888;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("========服务器已启动========");
System.out.println("服务器 ip: " + serverSocket.getInetAddress() + " port: " + serverSocket.getLocalPort());
//死循环监听时候有客户端连接
for (; ; ) {
//得到客户端
Socket socket = serverSocket.accept();
//构建异步线程
new ClientHandler(socket).start();
}
}
private static class ClientHandler extends Thread {
private Socket socket;
private Boolean flag = true;
public ClientHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
System.out.println("客户端 ip: " + socket.getLocalAddress() + " port: " + socket.getLocalPort());
//得到socket输入流
BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//得到socket输出流并转化为打印流
PrintStream socketPrinter = new PrintStream(socket.getOutputStream());
do {
//接受并打印客户端发送的信息
String receiveMsg = socketReader.readLine();
System.out.println("server receive msg: " + receiveMsg);
//将客户端发送的信息返回客户端
System.out.println("server response msg: " + receiveMsg);
socketPrinter.println(receiveMsg);
if ("bye".equalsIgnoreCase(receiveMsg)) {
flag = false;
}
} while (flag);
socketReader.close();
socketPrinter.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("客户端已退出");
}
}
}
}
TcpClient.java
package client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
public class TcpClient {
//读取数据超时
private static int SO_TIMEOUT = 3000;
//连接超时
private static int TIMEOUT = 5000;
private static int PORT = 8888;
public static void main(String[] args) throws IOException {
Socket socket = new Socket();
socket.setSoTimeout(SO_TIMEOUT);
socket.connect(new InetSocketAddress(InetAddress.getLocalHost(), PORT), TIMEOUT);
System.out.println("========已连接服务器========");
System.out.println("客户端 ip: " + socket.getLocalAddress() + " port: " + socket.getLocalPort());
System.out.println("服务器 ip: " + socket.getRemoteSocketAddress() + " port: " + socket.getPort());
//客户端向服务器端发送数据
try {
sendAndReceive(socket);
} catch (Exception e) {
e.printStackTrace();
System.out.println("连接异常断开");
}
}
public static void sendAndReceive(Socket socket) throws IOException {
boolean flag = true;
//构建键盘输入流
BufferedReader keyboardReader = new BufferedReader(new InputStreamReader(System.in));
//得到socket输入流
BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//得到socket输出流并转化为打印流
PrintStream socketPrinter = new PrintStream(socket.getOutputStream());
do {
//键盘读取一行并发送给服务器
String sendMsg = keyboardReader.readLine();
socketPrinter.println(sendMsg);
System.out.println("client send msg: " + sendMsg);
//得到服务器的响应
String receiveMsg = socketReader.readLine();
if ("bye".equalsIgnoreCase(receiveMsg)) {
flag = false;
System.out.println("========已退出服务器========");
} else {
System.out.println("client receive msg: " + receiveMsg);
}
} while (flag);
//资源释放
socketPrinter.close();
socketReader.close();
socket.close();
}
}
二.UDP通信
UdpSender.java
package server;
import java.io.IOException;
import java.net.*;
public class UdpSender {
private static final int PORT = 8089;
public static void main(String[] args) {
DatagramSocket socket;
final byte[] bytes = new byte[1024];
try {
//发送随机分配端口
socket = new DatagramSocket();
String sendMsg = "helloWorld";
DatagramPacket sendPacket = new DatagramPacket(sendMsg.getBytes(), 0, sendMsg.length());
sendPacket.setAddress(InetAddress.getLocalHost());
sendPacket.setPort(PORT);
//发送
System.out.println("UdpSender send: " + sendMsg);
socket.send(sendPacket);
//接受
DatagramPacket receivePacket = new DatagramPacket(bytes, bytes.length);
socket.receive(receivePacket);
String receiveMsg = new String(receivePacket.getData());
System.out.println("UdpSender receive: " + receiveMsg);
socket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
UdpReceiver,java
package client;
import java.io.IOException;
import java.net.*;
public class UdpReceiver {
private static final int PORT = 8089;
public static void main(String[] args) {
DatagramSocket socket;
final byte[] bytes = new byte[1024];
try {
//接收监听固定端口
socket = new DatagramSocket(PORT);
String sendMsg = "helloWorld";
//接收
DatagramPacket receivePacket = new DatagramPacket(bytes, bytes.length);
socket.receive(receivePacket);
String receiveMsg = new String(receivePacket.getData());
System.out.println("UdpReceiver receive: " + receiveMsg);
//发送
DatagramPacket responsePacket = new DatagramPacket(sendMsg.getBytes(), 0, sendMsg.length());
//将信息回复给发送者
responsePacket.setAddress(receivePacket.getAddress());
responsePacket.setPort(receivePacket.getPort());
System.out.println("UdpReceiver response: " + sendMsg);
socket.send(responsePacket);
socket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}