网络编程主要是通过Socket套接字,Java提供的API类
通过ip地址加端口可以唯一的标识一个进程。
客户端创建Socket。
Socket socket = new Socket("127.0.0.1",1000); //ip地址 +端口号
读取消息
// 创建输入流读取客户端消息BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));String message = input.readLine();System.out.println("Message from client: " + message);
给客户端发送消息
// 创建输出流向客户端发送消息
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
output.println("Hello from server!");
// 创建输出流向服务器发送消息PrintWriter output = new PrintWriter(socket.getOutputStream(), true);output.println("Hello from client!");// 创建输入流读取服务器的消息BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));String response = input.readLine();System.out.println("Message from server: " + response);
服务端
// 创建 ServerSocket,监听端口 1234ServerSocket serverSocket = new ServerSocket(1234);
输入流和输出流:Socket 通过输入流和输出流进行数据的发送和接收。
发送方:
package TCP实验八;import java.io.BufferedInputStream;
import java.net.ServerSocket;
import java.net.Socket;public class Server {public static void main(String[] args) throws Exception {ServerSocket server = new ServerSocket(5000);System.out.println("Server is listening on port 5000");Socket socket = server.accept();BufferedInputStream in = new BufferedInputStream(socket.getInputStream());byte[] buffer = new byte[1024];int bytesRead;// 循环读取消息while ((bytesRead = in.read(buffer)) != -1) {String message = new String(buffer, 0, bytesRead);System.out.print("Received: " + message);if (message.trim().equals("end")) {break;}}// 关闭资源in.close();socket.close();server.close();}
}
客户端:
package TCP实验八;import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;public class Client {public static void main(String[] args) throws IOException {Socket socket = new Socket("127.0.0.1", 5000);//output是输出流BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());Scanner sc = new Scanner(System.in);while (true) {String str = sc.nextLine();out.write(str.getBytes());out.write('\n'); // 发送换行符以标识消息结束out.flush(); // 刷新输出流if (str.equals("end")) {break;}}// 关闭输出流和 Socketout.close();socket.close();sc.close(); // 关闭 Scanner}
}