TCP发送实现

网络编程 TCP实现

TCP和UDP区别:TCP相当于打电话,双方需要同时在线连接,UDP相当于发邮件,一方发送,接收方不要求在线,在线即可接收发送方发送的消息

1. 编写发送方实体类 TcpSender(客户端)

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

public class TcpSender {
    public static void main(String[] args) throws IOException {
        // 服务器端的ip地址和端口
        InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
        int port = 9999;

        // 客户端发送接口
        Socket socket = new Socket(inetAddress, port);
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("你好!".getBytes());

        outputStream.close();
        socket.close();
    }
}

2. 编写接受方实体类 TcpReceive(服务器)

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

public class TcpReceive {
    public static void main(String[] args) throws IOException {
        // 服务器网络接收接口
        ServerSocket serverSocket = new ServerSocket(9999);

        // 接受发送方信息,进程阻塞状态
        Socket accept = serverSocket.accept();
        
        InputStream inputStream = accept.getInputStream();
        int len;
        byte[] bytes = new byte[1024];
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        while((len=inputStream.read(bytes)) != -1) {
            byteArrayOutputStream.write(bytes, 0, len);
        }
        System.out.println(byteArrayOutputStream.toString());
        
        inputStream.close();;
        byteArrayOutputStream.close();
        accept.close();
        serverSocket.close();
    }
}

3. 结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值