TCP的初步认识

什么是TCP

TCP(Transmission Control Protocol 传输控制协议)是一种面向连接(连接导向)的、可靠的、 基于IP的传输层协议。TCP在IP报文的协议号是6。TCP是一个超级麻烦的协议,而它又是互联网的基础,也是每个程序员必备的基本功。

TCP简单的demo例子

//客户端
public class TCPClientDemo01 {
    public static void main(String[] args) throws IOException {
        Socket socket =  null;
        OutputStream outputStream = null;
        try {
            //需要一个IP
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            //创建一个socket连接
             socket = new  Socket(inetAddress,10000);
            //发生消息 IO流
            outputStream = socket.getOutputStream();
            outputStream.write("你好,欢迎继续变强".getBytes());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(outputStream != null)
            outputStream.close();
            if(socket != null)
            socket.close();

        }
    }
}
//服务端
public class TcpServerDemo01 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            //1.我得有一个地址
             serverSocket = new ServerSocket(10000);
            while (true){
                //等待客户端连接管来
                socket = serverSocket.accept();
                inputStream = socket.getInputStream();
                //管道流
                byteArrayOutputStream = new ByteArrayOutputStream();
                byte [] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer,0,len);
                }
                System.out.println(byteArrayOutputStream.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(byteArrayOutputStream != null)
            byteArrayOutputStream.close();
            if(inputStream != null)
            inputStream.close();
            if(socket != null)
                socket.close();
            if(serverSocket != null)
            serverSocket.close();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值