一、总的来说,先了解它们的组成部分
代码语言:javascript复制基于TCP协议的服务器端
1.创建服务器套接字,绑定端口号(new ServerSocket(1008))
2.侦听客户连接,返回socker(listener.accept())
3.获输入、输出流
4.处理数据
5.关闭资源
基于TCP协议的客户端
1.创建客户端套接字,指定服务器的地址和端口号
2.获输入、输出流
3.处理数据
4.关闭资源
二、(1)服务端代码
代码语言:javascript复制package d04_test;/*
* zt
* 2020/8/10
* 18:16
*
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws Exception {
//1.创建
ServerSocket listener = new ServerSocket(10086);
//2.侦听
System.out.println("服务器已经启动");
Socket socket = listener.accept();
//3.获取输入输出流
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
//4.1处理数据(接收)
String data = br.readLine();
System.out.println("客户端说:" data);
//4.2处理数据(发送)
bw.write("你好啊,客户端");
bw.newLine();
bw.flush();
//5.关闭资源
bw.close();
br.close();
socket.close();
listener.close();
}
}
(2)客户端代码
代码语言:javascript复制package d04_test;/*
* zt
* 2020/8/10
* 18:16
*
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
//1.创建
Socket socket = new Socket("10.0.139.160",10086);
//2.获取输入流输出流
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
//3.1处理数据(发送)
bw.write("你好啊,服务器");
bw.newLine();
bw.flush();
//3.2处理数据(接收)
String str = br.readLine();
System.out.println("服务端跟你说:" str);
//4.关闭资源
bw.close();
socket.close();
}
}
(3)运行结果
先启动服务端
代码语言:javascript复制服务器已经启动
客户端说:你好啊,服务器
Process finished with exit code 0
再启动客户端
代码语言:javascript复制服务端跟你说:你好啊,客户端
Process finished with exit code 0