java+socket
时间: 2023-12-09 09:35:42 浏览: 69
Java中的Socket是一种网络通信协议,它是一种基于TCP/IP协议的网络通信协议。下面是一个简单的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 br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println("客户端发送的消息:" + line);
}
socket.close();
serverSocket.close();
}
}
// 客户端代码
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 br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
String line;
while ((line = br.readLine()) != null) {
pw.println(line);
}
socket.close();
}
}
```
这个例子中,服务端通过ServerSocket监听8888端口,等待客户端连接。客户端通过Socket连接到服务端的8888端口。服务端接收到客户端的连接请求后,通过socket.getInputStream()获取输入流,读取客户端发送的消息。客户端通过socket.getOutputStream()获取输出流,向服务端发送消息。
阅读全文