java代码简单实现客户端发送信息给服务端,服务端接收信息,然后服务端发送信息回给客户端
时间: 2023-08-10 14:28:53 浏览: 123
客户端代码:
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
// 获取输出流,向服务端发送信息
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.write("Hello Server!");
pw.flush();
socket.shutdownOutput();
// 获取输入流,接收服务端的信息
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String info;
while ((info = br.readLine()) != null) {
System.out.println("我是客户端,服务端说:" + info);
}
socket.shutdownInput();
// 关闭资源
br.close();
is.close();
pw.close();
os.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
服务端代码:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务端已启动,等待客户端连接...");
Socket socket = serverSocket.accept();
// 获取输入流,接收客户端的信息
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String info;
while ((info = br.readLine()) != null) {
System.out.println("我是服务端,客户端说:" + info);
}
socket.shutdownInput();
// 获取输出流,向客户端发送信息
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.write("Hello Client!");
pw.flush();
socket.shutdownOutput();
// 关闭资源
pw.close();
os.close();
br.close();
is.close();
socket.close();
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这段代码实现了客户端连接到服务端后,向服务端发送信息,服务端接收到信息后再向客户端发送信息。
阅读全文