java socket编程例子
时间: 2023-10-24 21:10:06 浏览: 120
Socket.zip_Java编程_Java_
下面是一个简单的 Java Socket 编程例子:
服务端代码:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器已启动,等待客户端连接...");
Socket socket = serverSocket.accept();
System.out.println("客户端已连接,客户端地址:" + socket.getInetAddress().getHostAddress());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println("客户端说:" + line);
}
reader.close();
socket.close();
serverSocket.close();
}
}
```
客户端代码:
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8888);
System.out.println("已连接服务器,服务器地址:" + socket.getInetAddress().getHostAddress());
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
String line;
while ((line = reader.readLine()) != null) {
writer.println(line);
}
writer.close();
reader.close();
socket.close();
}
}
```
阅读全文