Java实现TCP互发消息

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java实现TCP互发消息

~故事的小黄花~   2020-07-28 我要评论

本文着重为大家仔细讲解了Java实现TCP互发消息,文中代码实例讲解的非常细致,希望能够帮助到您,欢迎大家阅读和收藏

TCP客户端:

package tcp;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class TcpClient {
  public static void main(String[] args) {
    Socket socket =null;
    OutputStream os =null;
    try {
      //创建socket对象,指明服务器端的ip和端口号
      InetAddress inet = InetAddress.getByName("127.0.0.1");
      socket = new Socket(inet, 8888);
      //获取一个输出流,用于输出数据
      os = socket.getOutputStream();
      //写出数据的操作
      os.write("你好,我是客户端".getBytes());
    }catch(IOException e){
      e.printStackTrace();
    }finally {
      //资源的关闭
      if(os!=null){
        try{
          os.close();
        }catch (IOException e){
          e.printStackTrace();
        }
      }
      if(socket!=null){
        try {
          socket.close();
        }catch (IOException e){
          e.printStackTrace();
        }
      }
    }
  }
}

TCP服务端:

package tcp;

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

class TcpServer{
  public static void main(String[] args) {
    ServerSocket ss=null;
    Socket socket=null;
    InputStream is=null;
    ByteArrayOutputStream baos =null;
    try {
      //创建服务器端的ServerSocket,指明自己的端口
      ss = new ServerSocket(8888);
      //调用accept()表示接收来自于客户端的socket
      socket = ss.accept();
      //获取输入流中的数据
      is = socket.getInputStream();
      /*读取输入流中的数据(ByteArrayOutputStream可以把字节一次性记录下来,
      这样就可以避免一些字符的字节码不一致导致发送后解析出现乱码;
      ByteArrayOutputStream的功能与StringBuilder的作用有异曲同工之妙。)
      */
      baos = new ByteArrayOutputStream();
      byte[] buffer = new byte[5];
      int len;
      while ((len = is.read(buffer)) != -1) {
        baos.write(buffer, 0, len);
      }
      System.out.println(baos.toString());
    }catch (IOException e){
      e.printStackTrace();
    }
    finally{
      //关闭流
      if (baos!=null){
        try {
          baos.close();
        }catch (IOException e){
          e.printStackTrace();
        }
      }
      if (is!=null){
        try {
          is.close();
        }catch (IOException e){
          e.printStackTrace();
        }
      }
      if (socket!=null){
        try {
          socket.close();
        }catch (IOException e){
          e.printStackTrace();
        }
      }
      if (ss!=null){
        try {
          ss.close();
        }catch (IOException e){
          e.printStackTrace();
        }
      }
    }
  }
}

注意:在Intellij idea中运行时,需先打开两个端的平行运行设置,操作如下:

最后的运行结果如下:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们