案例一:客户端与服务端的连接
服务端:
package com.zbdx.tcp; import java.io.*; import java.net.ServerSocket; import java.net.Socket; /** * @Author: 王小甜 * @Description: * @Date Created in 2024-03-10 11:30 * @Modified By: */ public class TcpServer { public static void main(String[] args) throws IOException { //实例化服务端的对象 ServerSocket server = new ServerSocket(7777); //接收多个客户端的连接请求 boolean flag = true; while (flag){ System.out.println("服务端已经启动,等待客户端的连接:"); //等待客户端的连接 Socket client = server.accept(); System.out.println("有客户端连接了服务器-->" + client); //获取客户端的对象的输入输出对象 PrintStream printStream = new PrintStream(client.getOutputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));//获取字节输入流对应的缓冲流对象 //一直保持和客户端的通信 boolean boo = true; while (boo){ //处理业务(接收客户端发送的数据) String data = reader.readLine();//读取客户端发送过来的数据 //判断循环是否继续 if ("bye".equals(data)){ boo = false;//结束死循环 }else { System.out.println("客户端发送的数据为--->" + data); //给客户端发送消息 printStream.println("我是服务端我接受到了你的信息"); } } } } }
客户端:(可有多个,代码都一样)
package com.zbdx.tcp; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; /** * @Author: 王小甜 * @Description: * @Date Created in 2024-03-10 11:29 * @Modified By: */ public class TcpClient { public static void main(String[] args) throws IOException { //实例化客户端对象 Socket client = new Socket("127.0.0.1",7777); //获取输入输出流对象 PrintStream printStream = new PrintStream(client.getOutputStream());//获取客户端端字节输出流的打印流对象 BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));//获取输入流对象 BufferedReader readerConsole = new BufferedReader(new InputStreamReader(System.in));//获取控制台输入流的对象 //和服务器一直保持通信 boolean boo = true; while (boo){ System.out.println("=====请输入内容====="); //读取控制台输入的内容 String content = readerConsole.readLine(); printStream.println(content);//向服务端发送控制台输入的数据 //判断是否还和服务器进行通信(bye) if ("bye".equals(content)){ boo = false;//跳出死循环 }else { //读取服务端发送过来的消息 String data = reader.readLine();//读取服务端发送的消息 System.out.println("服务端发送过来的数据为-->" + data); } } //释放资源 printStream.close(); reader.close(); client.close(); } }
运行截图:
客户端:
服务端:
简单客户端(只有客户端):
package com.zbdx.tcp; import java.io.*; import java.net.Socket; /** * @Author: 王小甜 * @Description: * @Date Created in 2024-03-10 11:29 * @Modified By: */ public class TcpClient03 { public static void main(String[] args) throws IOException { //实例化客户端对象 Socket client = new Socket("127.0.0.1",7777); //获取输入输出流对象 OutputStream outputStream = client.getOutputStream(); InputStream inputStream = client.getInputStream(); //处理业务(给服务端发送一个字符串:你好服务端) PrintStream printStream = new PrintStream(outputStream); printStream.println("你好服务端");//向服务端发送数据 //读取读物短发送过来的消息 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String data = reader.readLine();//读取服务端发送的消息 System.out.println("服务端发送过来的数据为--->" + data); //释放资源 outputStream.close(); inputStream.close(); client.close(); } }