1:我们先去创建服务端Servier类
public class Server {
public static void main(String[] args) {
try {
//给客户端一个接口让其连接
ServerSocket serverSocket=new ServerSocket(8080);
System.out.println("服务器启动完成...监听中");
//开启监听 等待客户端的访问
Socket socket= serverSocket.accept();
//获取输入流,因为是客户端向服务器发送了数据
InputStream inputStream= socket.getInputStream();
//创建一个缓冲流
BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
String info=null;
while ((info=br.readLine())!=null){
System.out.println("这里是服务端 客户端说:"+info);
}
//向客户端做出响应
OutputStream outputStream=socket.getOutputStream();
info="这里是服务端我们接受到了你的消息";
outputStream.write(info.getBytes());
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2:我们接下来去创建客户端Client类
public class Client {
public static void main(String[] args) {
try {
Socket socket=new Socket("localhost",8080);
OutputStream outputStream=socket.getOutputStream();
String info="向服务端发送消息!";
//输出!(输出流向服务器发送数据)
outputStream.write(info.getBytes());
socket.shutdownOutput();
//接收服务端的响应
InputStream inputStream1 = socket.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(inputStream1));
while ((info=br.readLine())!=null){
System.out.println("接受到服务端的响应"+info);
}
//刷新缓冲区
outputStream.flush();
outputStream.close();
inputStream1.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
3:然后我们先去启动服务端,服务端显示启动,然后再去启动客户端,每运行一次客户端,服务端都会接收到一条消息!,并且回复客户端!