Java Socket(套接字)通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄。应用程序通常通过"套接字"向网络发出请求或者应答网络请求。
Socket和ServerSocket类库位于java.net包中。ServerSocket用于服务器端,Socket是建立网络连接时使用的。在连接成功时,应用程序两端都会产生一个Socket实例,操作这个实例,完成所需的会话。对于一个网络连接来说,套接字是平等的,并没有差别,不因为在服务器端或在客户端而产生不同级别。不管是Socket还是ServerSocket它们的工作都是通过SocketImpl类及其子类完成的。
重要的Socket API:
java.net.Socket继承于java.lang.Object,有八个构造器,其方法并不多,下面介绍使用最频繁的三个方法,其它方法大家可以见JDK-1.3文档。
. Accept方法用于产生"阻塞",直到接受到一个连接,并且返回一个客户端的Socket对象实例。"阻塞"是一个术语,它使程序运行暂时"停留"在这个地方,直到一个会话产生,然后程序继续;通常"阻塞"是由循环产生的。
. getInputStream方法获得网络连接输入,同时返回一个InputStream对象实例。
. getOutputStream方法连接的另一端将得到输入,同时返回一个OutputStream对象实例。
注意:其中getInputStream和getOutputStream方法均会产生一个IOException,它必须被捕获,因为它们返回的流对象,通常都会被另一个流对象使用。
更多Java Socket详细教程:
https://www.cnblogs.com/yiwangzhibujian/p/7107785.html
下面是利用socket进行客户端和服务端的通信:
client.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
import java.io.*; import java.net.*; import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; @SuppressWarnings("restriction") public class Client extends Application { // IO streams DataOutputStream toServer = null; DataInputStream fromServer = null; @Override // Override the start method in the Application class public void start(Stage primaryStage) { // Panel p to hold the label and text field BorderPane paneForTextField = new BorderPane(); paneForTextField.setPadding(new Insets(5, 5, 5, 5)); paneForTextField.setStyle("-fx-border-color: green"); paneForTextField.setLeft(new Label("Enter a radius: ")); TextField tf = new TextField(); tf.setAlignment(Pos.BOTTOM_RIGHT); paneForTextField.setCenter(tf); BorderPane mainPane = new BorderPane(); // Text area to display contents TextArea ta = new TextArea(); mainPane.setCenter(new ScrollPane(ta)); mainPane.setTop(paneForTextField); // Create a scene and place it in the stage Scene scene = new Scene(mainPane, 450, 200); primaryStage.setTitle("Client"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage tf.setOnAction(e -> { try { // Get the radius from the text field double radius = Double.parseDouble(tf.getText().trim()); // Send the radius to the server toServer.writeDouble(radius); toServer.flush(); // Get area from the server double area = fromServer.readDouble(); // Display to the text area ta.appendText("半径为 " + radius + "\n"); ta.appendText("服务器计算结果为: " + area + '\n'); } catch (IOException ex) { System.err.println(ex); } }); try { // Create a socket to connect to the server Socket socket = new Socket("localhost", 8888); // Socket socket = new Socket("130.254.204.36", 8000); // Socket socket = new Socket("drake.Armstrong.edu", 8000); // Create an input stream to receive data from the server fromServer = new DataInputStream(socket.getInputStream()); // Create an output stream to send data to the server toServer = new DataOutputStream(socket.getOutputStream()); } catch (IOException ex) { ta.appendText(ex.toString() + '\n'); } } /** * The main method is only needed for the IDE with limited * JavaFX support. Not needed for running from the command line. */ public static void main(String[] args) { launch(args); } } |
Server.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
import java.io.*; import java.net.*; import java.util.Date; import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Scene; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextArea; import javafx.stage.Stage; public class Server extends Application { @Override // Override the start method in the Application class public void start(Stage primaryStage) { // Text area for displaying contents TextArea ta = new TextArea(); // Create a scene and place it in the stage Scene scene = new Scene(new ScrollPane(ta), 450, 200); primaryStage.setTitle("Server"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage new Thread( () -> { try { // Create a server socket ServerSocket serverSocket = new ServerSocket(8888); Platform.runLater(() -> ta.appendText("服务器开始时间 " + new Date() + '\n')); // Listen for a connection request Socket socket = serverSocket.accept(); // Create data input and output streams DataInputStream inputFromClient = new DataInputStream( socket.getInputStream()); DataOutputStream outputToClient = new DataOutputStream( socket.getOutputStream()); while (true) { // Receive radius from the client double radius = inputFromClient.readDouble(); // Compute area double area = radius * radius * Math.PI; // Send area back to the client outputToClient.writeDouble(area); Platform.runLater(() -> { ta.appendText("客户端传来的半径为: " + radius + '\n'); ta.appendText("面积为: " + area + '\n'); }); } } catch(IOException ex) { ex.printStackTrace(); } }).start(); } /** * The main method is only needed for the IDE with limited * JavaFX support. Not needed for running from the command line. */ public static void main(String[] args) { launch(args); } } |
效果:
注意本实例对于接口8888端口尚未关闭处于Listening状态,会导致其它程序无法使用8888端口,如果要关闭请到任务管理器关闭占用8888端口的进程!