基于TCP—Socket通讯

通讯过程
在这里插入图片描述

客户端:

public class MyClient {
    public static void main(String[] args) throws IOException {
        //客户端 连接Server发布的服务
        Socket socket = new Socket("127.0.0.1", 8080);

        //客户端向服务端做出反馈(向服务端发送消息)
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello server".getBytes());

        //接受服务端发送的消息 InputStream
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        inputStream.read(bytes);
        System.out.println(new String(bytes));

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

public class MyServer {
    public static void main(String[] args) throws IOException {
        //绑定服务的端口,ip:为本机Ip
        //暴漏了一个 服务,该服务的地址: 本机ip:9999
        ServerSocket serverSocket = new ServerSocket(8080);
        Socket accept = serverSocket.accept();
        System.out.println("与客户端连接成功");

        //接受客户端的消息
        InputStream inputStream = accept.getInputStream();
        byte[] bytes = new byte[1024];
        inputStream.read(bytes);
        System.out.println(new String(bytes));

        //服务端向客户端发送消息 Output
        OutputStream outputStream = accept.getOutputStream();
        outputStream.write("hello client".getBytes());

        //关闭通讯
        serverSocket.close();
        accept.close();
        inputStream.close();
        outputStream.close(); 
    }
}

服务器端给客户端发送文件:
在这里插入图片描述
服务器端:

public class FileServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        Socket accept = serverSocket.accept();
        System.out.println("已接受客户端");
        OutputStream outputStream = accept.getOutputStream();

        //从硬盘写入内存当中
        FileInputStream in = new FileInputStream("G:\\video.zip");
        byte[] bytes = new byte[1024];
        int len =-1;
        while ((len = in.read(bytes))!= -1){
            outputStream.write(bytes,0,len);
        }
        outputStream.close();
        serverSocket.close();
        accept.close();
        in.close();
    }
}

客户端:

public class FileClient {
    public static void main(String[] args) throws IOException {
        Socket socket1 = new Socket("127.0.0.1", 8080);
        FileOutputStream outputStream = new FileOutputStream("G:\\aa.zip");
        InputStream inputStream = socket1.getInputStream();
        int len = -1;
        byte[] bytes = new byte[1024];
        while ((len = inputStream.read(bytes)) != -1){
            outputStream.write(bytes,0,len);
        }
        socket1.close();
        outputStream.close();
        inputStream.close();
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值