• 例子1:客户端发送信息给服务端,服务端将数据显示在控制台上
      ```java package com.atguigu.java2;

    import org.junit.Test;

    import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket;

    /**

    • 实现TCP的网络编程
    • 例子1:客户端发送信息给服务端,服务端将数据显示在控制台上 *
    • @author Dxkstart
    • @create 2021-06-04 18:07 */ public class TCPTest {

      @Test public void client() {//客户端

      1. Socket socket = null;
      2. OutputStream os = null;
      3. try {
      4. //1.创建Socket对象,指明服务器端的ip和端口号
      5. InetAddress inet = InetAddress.getByName("127.0.0.1");
      6. socket = new Socket(inet,8899);
      7. //2.获取一个输出流,用于输出数据
      8. os = socket.getOutputStream();
      9. //3.写出数据的操作
      10. os.write("你好我是客户端MM".getBytes());
      11. } catch (IOException e) {
      12. e.printStackTrace();
      13. } finally {
      14. //4.资源的关闭
      15. try {
      16. if(os != null) {
      17. os.close();
      18. }
      19. } catch (IOException e) {
      20. e.printStackTrace();
      21. }
      22. try {
      23. if(socket != null) {
      24. socket.close();
      25. }
      26. } catch (IOException e) {
      27. e.printStackTrace();
      28. }
      29. }

      }

    1. @Test
    2. public void server(){//服务端
    3. ServerSocket ss = null;
    4. InputStream is = null;
    5. Socket socket = null;
    6. ByteArrayOutputStream baos = null;
    7. try {
    8. //1.创建服务器短的ServerSocket,指明自己的端口号
    9. ss = new ServerSocket(8899);
    10. //2.调用accept()表示接收来自于客户端的socket
    11. socket = ss.accept();
    12. //3.获取输入流
    13. is = socket.getInputStream();
    14. //不建议这么写,可能会出现乱码,一个汉字占3个字节

    // byte[] buffer = new byte[200]; // int len; // while((len = is.read(buffer)) != -1 ){ // String str = new String(buffer, 0, len); // System.out.print(str); // }

    1. //4.读取输入流中的数据
    2. baos = new ByteArrayOutputStream();
    3. byte[] buffer = new byte[5];
    4. int len;
    5. while ((len = is.read(buffer)) != -1){
    6. baos.write(buffer,0,len);
    7. }
    8. System.out.println(baos.toString());
    9. } catch (IOException e) {
    10. e.printStackTrace();
    11. } finally {
    12. //5.资源的关闭
    13. try {
    14. if(baos != null) {
    15. baos.close();
    16. }
    17. } catch (IOException e) {
    18. e.printStackTrace();
    19. }
    20. try {
    21. if(is != null) {
    22. is.close();
    23. }
    24. } catch (IOException e) {
    25. e.printStackTrace();
    26. }
    27. try {
    28. if(ss != null) {
    29. ss.close();
    30. }
    31. } catch (IOException e) {
    32. e.printStackTrace();
    33. }
    34. try {
    35. if(socket != null) {
    36. socket.close();
    37. }
    38. } catch (IOException e) {
    39. e.printStackTrace();
    40. }
    41. }
    42. }

    }

    ```