TCP实现文字与文件的传输

服务端代码来接收图片文件

package  com;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TestServerSocket {
    
    
    public static void main(String[] args) throws Exception {
    
    
        //创建一个端口号,自己命名
        ServerSocket ss = new ServerSocket(9900);
        //接受传输的数据
        Socket socket = ss.accept();
        //获取输入流
       InputStream in = socket.getInputStream();
       //通过输出流来输出文件
        File files = new File("2.jpg");//图片的路径
        FileOutputStream file = new FileOutputStream(files);
        int length;
        byte [] bytes = new  byte[1024];
        while((length = in.read(bytes)) != -1){
    
    
            file.write(bytes,0,length);
        }
        //告诉客户端,已经接收完毕
        OutputStream out = socket.getOutputStream();
        out.write("接收完毕,可以关了".getBytes());
        out.close();
        file.close();
        in.close();
        socket.close();
        ss.close();
    }
}

客户端收到反馈

package com;
import java.io.*;
import java.net.Socket;
public  class TestSocket  {
    
    
    public static void main(String[] args) throws Exception{
    
    
        //通过IP和端口号连接客服端,这里连的为本机的IP和端口号
        Socket socket = new Socket("127.0.0.1",9900);
        //创建IO流来将数据输入到服务端
        OutputStream out = socket.getOutputStream();
        //创建输入流读入文件
        File files = new File("1.jpg");
        FileInputStream file = new FileInputStream(files);
        //传输文件
        int length;
        byte bytes [] = new byte[1024];
        while((length = file.read(bytes)) != -1){
    
    
            out.write(bytes,0,length);
        }
        //传输完毕
        socket.shutdownOutput();
        //接收服务端的信息,并输出
        InputStream in = socket.getInputStream();
        ByteArrayOutputStream pip =  new ByteArrayOutputStream();
        while((length = in.read(bytes)) != -1){
    
    
            pip.write(bytes,0,length);
        }
        System.out.println(pip.toString());
        pip.close();
        in.close();
        file.close();
        out.close();
        socket.close();
    }
}

Guess you like

Origin blog.csdn.net/Badman0726/article/details/118829020