TCP通信
1.需要一个服务端ServerSocket和一个客户端Socket
2.代码:
1)服务端:ServerSocket
package shapes; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class ServerSocketDemo { public static void main(String[] args) { // TODO Auto-generated method stub try { // 创建一个ServerSocket ServerSocket ss = new ServerSocket(2000); // 侦听客户端Socket Socket s = ss.accept(); // 获取输入流 InputStream is = s.getInputStream(); byte[] bys = new byte[1024]; int len = is.read(bys); String data = new String(bys,0,len); System.out.println("数据是:" + data); //释放资源 s.close(); ss.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
2)客户端:Socket
package shapes; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub try { // 创建Socket Socket s = new Socket("192.168.90.114", 2000); // 获取输出流,写数据 OutputStream os = s.getOutputStream(); os.write("hell,tcp!".getBytes()); //释放资源 s.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
3.结果:先运行服务端后再运行客户端
参阅:https://www.bilibili.com/video/BV1vk4y117fU?p=347