import java.io.*;import java.net.*;public class SocketClient { public static void main(String[] args) { try { // 创建Socket客户端并连接到服务器 Socket socket = new Socket("localhost", 9999); // 获取输出流并发送数据到服务器 OutputStream os = socket.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os); BufferedWriter bw = new BufferedWriter(osw); String message = "Hello from SocketClient!"; bw.write(message); bw.flush(); System.out.println("Message sent to the server: " + message); // 关闭连接 bw.close(); osw.close(); os.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } }} 这段代码对应的本地Socket服务器,用代码展示
时间: 2024-02-10 12:11:10 浏览: 174
import java.net.*;import java.io.*;
5星 · 资源好评率100%
以下是对应的本地Socket服务器代码示例:
```
import java.io.*;
import java.net.*;
public class SocketServer {
public static void main(String[] args) {
try {
// 创建ServerSocket对象并监听9999端口
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("Waiting for client connection...");
// 等待客户端连接
Socket socket = serverSocket.accept();
// 获取输入流并读取客户端发送的数据
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
char[] buf = new char[1024];
int len = br.read(buf);
String message = new String(buf, 0, len);
System.out.println("Message received from the client: " + message);
// 关闭连接
br.close();
isr.close();
is.close();
socket.close();
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
该服务器代码会监听9999端口,等待客户端连接。一旦有客户端连接,就会获取客户端发送的数据并打印出来,然后关闭连接。
阅读全文