谨以此篇,记录TCP编程,方便日后查阅笔记文章来源:https://www.toymoban.com/news/detail-699589.html
注意:用BufferedWriter write完后,一定要flush;否则字符不会进入流中。去看源码可知:真正将字符写入的不是write(),而是flush()。
服务器端代码:
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文章来源地址https://www.toymoban.com/news/detail-699589.html
到了这里,关于socket的使用 | TCP/IP协议下服务器与客户端之间传送数据的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!