内容出处https://study.163.com/course/courseMain.htm?courseId=1209171838
客户端源代码
package my; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; public class test { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //一个Socket代表一路连接 Socket sock = new Socket(); //连接至服务器 sock.connect(new InetSocketAddress("192.168.1.101", 2019)); //InputStream用于接收数据,OutputStream用于发送数据 InputStream inputStream = sock.getInputStream(); OutputStream outputStream = sock.getOutputStream(); //发送数据 String outputMsg = "Hello"; byte[] outputData = outputMsg.getBytes("UTF-8"); outputStream.write(outputData); System.out.println(">>: " + outputMsg); //接收数据 byte[] inputData = new byte[4000]; int n = inputStream.read(inputData); String inputMsg = new String(inputData, 0, n, "UTF-8"); System.out.println("<<:" + inputMsg); //关闭连接 sock.close(); } }
服务器源代码
package my; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class test { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //建立服务器,服务于2019端口 ServerSocket serverSock = new ServerSocket(2019); System.out.println("服务器启动,等待连接..."); while(true) { //监听请求,阻塞等待,直接有客户端发起连接... Socket conn = serverSock.accept(); //从连接里得到输入输出流 //InputStream:可以读取客户端发来的数据 //OutputStream:可以发送数据给客户端 InputStream inputStream = conn.getInputStream(); OutputStream outputStream = conn.getOutputStream(); //接收数据 byte[] inputData = new byte[4000]; int n = inputStream.read(inputData); if(n<=0) { conn.close(); continue; } //发送数据 String inputMsg = new String(inputData, 0, n, "UTF-8"); System.out.println("GOT:" + inputMsg); String outputMsg = "Welcome!"; byte[] outputData = outputMsg.getBytes("UTF-8"); outputStream.write(outputData); System.out.println("ECHO:" + outputMsg + "\n"); //关闭连接 conn.close(); } } }
演示
程序员阿飞
2021年5月25日
原文:https://www.cnblogs.com/nxopen2018/p/14810377.html