服务器端代码:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;public class theServer {public static void main(String[] args) throws IOException {ServerSocket serverSocket = new ServerSocket(9999); // 该行代码作用:让服务器监听9999端口Socket socket = serverSocket.accept();InputStream inputStream = socket.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
// byte[] bytes = new byte[1024];
// int readLine = 0;
// while ((readLine = inputStream.read(bytes)) != -1) {
// System.out.print(new String(bytes, 0, readLine));
// }
// socket.shutdownInput();String readStr = reader.readLine();System.out.println(readStr);OutputStream outputStream = socket.getOutputStream();BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
// outputStream.write("server: hi client".getBytes());
// socket.shutdownOutput();writer.write("server: hi client");writer.newLine();writer.flush();writer.close(); // 后打开的流,先关闭reader.close();socket.close();serverSocket.close(); // 先打开的流,后关闭}
}
客户端代码:
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;public class theClient {public static void main(String[] args) throws IOException {Socket socket = new Socket(InetAddress.getLocalHost(),9999); // 该行代码作用:让客户端连接到服务器的9999端口OutputStream outputStream = socket.getOutputStream();BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
// outputStream.write("client: hi server".getBytes());writer.write("client: hi server");
// socket.shutdownOutput();writer.newLine();writer.flush();InputStream inputStream = socket.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
// byte[] bytes = new byte[1024];
// int readLine = 0;
// while ((readLine = inputStream.read(bytes)) != -1) {
// System.out.print(new String(bytes, 0, readLine));
// }
// socket.shutdownInput();String readStr = reader.readLine();System.out.println(readStr);reader.close();writer.close();socket.close();}
}
运行后结果:
服务器端:
客户端: