在Java中,Socket数据传输主要涉及到两个类:java.net.Socket
(用于客户端)和java.net.ServerSocket
(用于服务器端)。以下是一个简单的示例,展示了如何使用这两个类进行数据传输。
服务器端
accept()
方法,等待客户端连接。accept()
方法返回一个新的Socket对象,用于与客户端进行通信。getInputStream()
)和输出流(getOutputStream()
)进行数据读写。客户端
getInputStream()
)和输出流(getOutputStream()
)进行数据读写。以下是一个简单的Java Socket数据传输示例:
服务器端代码
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
int port = 12345;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server is listening on port " + port);
Socket socket = serverSocket.accept();
System.out.println("Client connected");
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String message = reader.readLine();
System.out.println("Received message: " + message);
OutputStream outputStream = socket.getOutputStream();
PrintWriter writer = new PrintWriter(outputStream, true);
writer.println("Hello from server");
socket.close();
serverSocket.close();
}
}
客户端代码
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
String serverAddress = "localhost";
int port = 12345;
Socket socket = new Socket(serverAddress, port);
System.out.println("Connected to server");
OutputStream outputStream = socket.getOutputStream();
PrintWriter writer = new PrintWriter(outputStream, true);
writer.println("Hello from client");
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String message = reader.readLine();
System.out.println("Received message: " + message);
socket.close();
}
}
在这个示例中,服务器监听端口12345,并在接收到客户端连接后,与客户端进行数据交换。客户端连接到服务器并发送一条消息,然后服务器回复一条消息。最后,双方都关闭了Socket连接。