谨以此篇,记录TCP编程,方便日后查阅笔记
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(); // 结束标记,让对方(客户端)socket可以使用outputStream流
writer.write("server: hi client");
writer.newLine(); // 使用字符流的话,可以用“socket.shutdownInput()”作为结束标记,也可以用“writer.newLine()”作为结束标记;使用newLine作为结束标记,对应的,在读的时候需要使用readLine来读数据
writer.flush(); // 用BufferedWriter write完后,一定要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(); // // 结束标记,让对方(服务器端)socket可以使用outputStream流
writer.newLine(); // 使用字符流的话,可以用“writer.newLine()”作为结束标记
writer.flush(); // 用BufferedWriter write完后,一定要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();
}
}
服务器端:
客户端:
参考资料:
https://www.bilibili.com/video/BV1fh411y7R8?p=669&vd_source=07ed824bba84f399accbac1be9f9f505